我想将一个事件绑定到我视图中图像的onerror
。
onerror
不会冒泡,所以我不能使用events: { 'error img' : 'imgEvent_' }
。
我怎样才能把它绑定到像this.el.querySelector('img').on('error, imgEvent_, this);
这样的东西
请不要内联HTML。
忘了提一下..。我没有使用任何DOM库,所以没有jQuery之类的。
我这样做了:
this.el.queryelector('img').onerror = this.myFunction_;
我现在的问题是,在this.myFunction_
中,this
实际上是img
元素……我仍然需要访问myFunction_
所在的this
。我该如何解决这个问题?
发布于 2013-03-27 20:02:12
您不能在事件映射中绑定onerror,因为这里的Backbone.js将事件从文档委托给指定的元素(http://api.jquery.com/delegate/):
events: { 'error img': 'callaback' }
意思是这样的:
$(document).on('error', 'img', callback);
让文档出错吗?它可以委托给img吗?
我建议您自己绑定它:
this.$('img').on('error', callback);
另外,请原谅我的英语。
发布于 2015-11-30 15:28:00
您可以从first argument given to the error function的target属性引用图像元素。您可以使用Underscore's bind method将该方法绑定到您的视图。
this.el.queryelector('img').onerror = _.bind(function(error){
var img = error.target;
this.myFunction_();
}, this);
如果您只需要myFunction
始终引用视图,而不关心图像或其他什么,那么可以使用
this.el.queryelector('img').onerror = _.bind(this.myFunction_, this);
或者Underscore's bindAll method。
_.bindAll(this, 'myFunction_');
this.el.queryelector('img').onerror = this.myFunction_;
https://stackoverflow.com/questions/15668203
复制相似问题