1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mattio
  • 2,014
  • 3
  • 24
  • 37

1 Answers1

0

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Man I hate silly mistakes like that. Thanks for the help! I went with: evt.currentTarget.src = "assets/images/_noimage.gif"; – Mattio Nov 07 '13 at 21:36