Using backbonejs view, what is the best way to attach an “onload” event to an image tag?

喜夏-厌秋 提交于 2019-12-03 17:02:57

问题


I want to attach an "onload" event for an image in a backbonejs view. I am currently including it in the "events" as "load img":"function", but it is not getting fired off.

Any suggestions for doing this?


回答1:


Backbone's event handling is based on delegate and delegate can only be used with events that bubble. The problem is that load events do not bubble; from the HTML5 specification:

If the download was successful
Set the img element to the completely available state, update the presentation of the image appropriately, and fire a simple event named load at the img element.

And a simple event does not bubble:

Firing a simple event named e means that an event with the name e, which does not bubble (except where otherwise stated) [...]

So you'll have to hook up a handler by hand with something like this:

render: function() {
    var self = this;
    this.$el.append(some_html_with_img_elements);
    this.$el.find('img').on('load', function() { self.img_loaded() });
    return this;
}

Demo: http://jsfiddle.net/ambiguous/c7wH2/



来源:https://stackoverflow.com/questions/9829580/using-backbonejs-view-what-is-the-best-way-to-attach-an-onload-event-to-an-im

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!