简体   繁体   中英

Working with an image error event in a Backbone view

Within an Underscore template used by a Backbone view I have an image. I'm trying to attach to the error event and change the image source if the original image is not found.

Based on this similar question , I took the following approach:

render: function() { 
    var self = this;

    this.$el.html( this.template( { person: this.model.toJSON() } ) ); 

    this.$el.find('img.employee-image').on('error', function(evt) { this.src = "assets/images/_noimage.gif"; });

    return this;
}

This works perfectly well, but if I try to move the changing of the src to a separate method in the view, the method will be called but the image will not change.

render: function() { 
    var self = this;

    this.$el.html( this.template( { person: this.model.toJSON() } ) ); 

    this.$el.find('img.employee-image').on('error', function(evt) { self.handleMissingImage(evt); });

    return this;
},

handleMissingImage: function(evt) {
    // This by itself did not work.
    // this.src = "assets/images/_noimage.gif";

    var i = $(evt.currentTarget);
    i.src = "assets/images/_noimage.gif";
    console.log(i.src);
}

Logging the src out shows "assets/images/_noimage.gif" but the image will not appear. I know it exists because the first approach outlined above works fine.

What am I missing here?

I think your problem is right here:

i.src = "assets/images/_noimage.gif";

In your handleMissingImage function you say:

i = $(evt.currentTarget);

so i is a jQuery object, not a raw DOM element. That means that you want to say i.attr('src', ...) to change the src attribute or don't bother wrapping evt.currentTarget at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM