如何委派一个"负载" DOM事件? [英] how to delegate a "load" DOM event?

查看:112
本文介绍了如何委派一个"负载" DOM事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个函数时,引发了load事件:

I would like to call a function when a "load" event is triggered:

events: {
    "load #eventPicture" : "_resizeHeaderPic"
}

我不想做这样的事这$(#eventPicture)上(负荷,_resizeHeaderPic); ,因为我有很多的观点(这是一个的单页应用的),我可以回去显示另一种观点是加载图像之前。所以,如果我再回来这个观点,我想有两个侦听器的load事件。对?通过把一切都在我的事件哈希,我能 undelegate 正常。
但似乎负载#eventPicture不工作。任何建议?

I don't want to do something like this.$("#eventPicture").on("load", _resizeHeaderPic); because I have a lot of views (it's a Single Page App) and I could go back to show another view before the image was loaded. So, if I then come back to this view I would have two listener for that "load" event. Right? By putting everything in my events hash, I can undelegate properly. But it seems that "load #eventPicture" does not work. Any suggestion?

推荐答案

您不能跟踪负荷从骨干事件事件因为这个事件只在图像例如火灾和不起泡。所以, Backbone.View $ EL 无法跟踪它。

You cannot track load event from Backbone events because this event fires only on image instance and doesn't bubble. So Backbone.View's $el cannot track it.

<一个href=\"http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached\">jQuery回调的图像加载(即使当图像被缓存)

我会建议使用另一个概念(的jsfiddle )。这是最好的做法:

I would suggest to use another concept (JSFiddle). This is best practice:

var LayoutView = Backbone.View.extend({
    el : '[data-container]',
    show : function (view) {
        // remove current view
        this.$view && this.$view.remove();
        // save link to the new view
        this.$view = view;
        // render new view and append to our element
        this.$el.html(this.$view.render().el);
    }
});

var ImageView = Backbone.View.extend({
    template : _.template('<img src="https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-prn2/1375054_4823566966612_1010607077_n.jpg"/>'),
    render : function () {
        this.$el.html(this.template());
        this.$('img').on('load', _.bind(this.onLoad, this));
        return this;
    },
    onLoad : function () {
        console.log('onLoad');
    }
});

var OtherView = Backbone.View.extend({
    template : _.template('lalala'),
    render : function () {
        this.$el.html(this.template());
        return this;
    }
});

var Router = Backbone.Router.extend({
    routes : {
        'other' : 'other',
        '*any' : 'image'
    },
    initialize : function (options) {
        this.layout = new LayoutView();
    },
    other : function () {
        this.layout.show(new OtherView());
    },
    image : function () {
        this.layout.show(new ImageView());
    }
});

new Router();
Backbone.history.start();

这篇关于如何委派一个&QUOT;负载&QUOT; DOM事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆