3

GWT: 2.6.1
I would like to execute an action when an image is loaded (image src).

I tried this, but the onLoad event is never fired :

    final Image img = new Image();
    img.addLoadHandler( new LoadHandler()
    {

        @Override
        public void onLoad( LoadEvent event )
        {
            //action
        }
    } );

    img.setUrl( "/image.png" );

Then I tried this :

    final Image img = Image.wrap( Document.get().createImageElement() );
    img.addLoadHandler( new LoadHandler()
    {

        @Override
        public void onLoad( LoadEvent event )
        {
            //action
        }
    } );

    img.setUrl( "/image.png" );

And it worked... I don't understand why the first code do nothing.

Important: In this two examples, I don't put the Image object into the dom (= Image isn't attached).

In this question, it seems that the cause is that the Image isn't attached. But in my second sample code, the image isn't attached too ? right ?

Community
  • 1
  • 1
puglic
  • 109
  • 11

1 Answers1

1

If you take a look into documentation of the wrap() method, it says This element must already be attached to the document. . So, when you actually check source of the wrap() it calls onAttach() which actually registers event handlers to the DOM element. So the difference is that Image object thinks element is attached while it is not in that state.

Now, on entrance of the wrap() there is assertion that checks the condition is met. Though you need to enable assertions to have them effective.

okrasz
  • 3,866
  • 24
  • 15
  • I don't understand why we must attach the element to handle the load event, cause it's not an obligation in Javascript.. – puglic Dec 31 '14 at 15:16