gruuuvy
gruuuvy

Reputation: 2129

How do I bind onerror to an image inside a Backbone view?

I want to bind an event to the onerror of an image inside my view.

onerror doesn't bubble up so I can't use events: { 'error img' : 'imgEvent_' }.

How can I bind this to maybe something like this.el.querySelector('img').on('error, imgEvent_, this);?

No inline HTML please.

Forgot to mention... I don't use any DOM libraries so no jQuery and such.

I did this:

this.el.queryelector('img').onerror = this.myFunction_;

My problem now is that within this.myFunction_, this is actually the img element... I still need to access the this where myFunction_ resides. How do I solve this?

Upvotes: 2

Views: 1537

Answers (2)

iabw
iabw

Reputation: 1108

You can reference the image element from the target property of the first argument given to the error function. You can bind the method to your View using Underscore's bind method.

this.el.queryelector('img').onerror = _.bind(function(error){
    var img = error.target;
    this.myFunction_();
}, this);

If you just need myFunction to always refer to the view and don't care about the image or whatever, you can use

this.el.queryelector('img').onerror = _.bind(this.myFunction_, this);

or Underscore's bindAll method.

_.bindAll(this, 'myFunction_');
this.el.queryelector('img').onerror = this.myFunction_;

Upvotes: 1

Dmytro Krasun
Dmytro Krasun

Reputation: 1742

You can't bind onerror in events map, because here Backbone.js delegate events from document to specified element (http://api.jquery.com/delegate/):

events: { 'error img': 'callaback' }

Mean something like this:

$(document).on('error', 'img', callback); 

Have document onerror? And can it be delegated to img?

I recommend you to bind it yourself:

this.$('img').on('error', callback);

P.S. Excuse me for my English.

Upvotes: 4

Related Questions