0

I'm trying to add load event to img tag when the src of the image is changed. The image is deleted and reattached due to a plugin, so I can't really changed that. This is my simplified HTML

<div class="twitter">
    <img src="picture.jpg" />
</div>

And this is my Backbone script

var TwiterView = Backbone.View.extend( {
    render : function() {
        var self = this;

        this.$el.on('load', 'img', function() {
            self.updateTwitterPreview();
        }).each(function() {
            if(this.complete) $(this).trigger('load');
        });

        this.$el.find('img').on("remove", function () {
            alert("Element was removed"); // This one got fired when the event is removed
        });
        return this;
    },
    updateTwitterPreview: function() {
        alert('test'); // This one got fired when the page is loaded the first time, but not when the image is changed
    }
});

I'm trying to use delegated event but it didn't really work.

toy
  • 11,711
  • 24
  • 93
  • 176
  • your script is incomplete. Where's the events hash? – Patrick Gunderson Nov 06 '14 at 01:34
  • The events is left out because of this http://stackoverflow.com/questions/19335702/how-to-delegate-a-load-dom-event that's why I attach the event manually. – toy Nov 06 '14 at 01:35
  • You can't use delegated events without the events hash. You need to rerender your view every time in order to get the event listener attached to your new `` – Patrick Gunderson Nov 06 '14 at 18:07

1 Answers1

0

I think this.$el returns the actual image element

For delegated event you should use a parent element

instead of this

this.$el.on('load', 'img', function() {

try using this

$(document).on('load', 'img', function() {

here $(document) element can be anything which is parent to the image elements

Cerlin
  • 6,622
  • 1
  • 20
  • 28