使用backbone.js和jQuery进行事件绑定点击

Ind*_*ial 6 jquery javascript-events backbone.js

我需要在我的backbone.js-view中绑定两个事件才能切换菜单.我们的想法是,如果单击带有id的按钮,则#toggler菜单会出现,并且#menu元素外的任何单击都将隐藏菜单.

不幸的是,outsideMenuHandler()无论是否点击#menu元素,我都无法使用骨干的事件绑定,而无需每次点击都调用.

我应该改变什么来使这项工作?

这是我在backbone.js中所做的,它不能按预期工作:

myView = Backbone.View.extend({

    events: {
        'click #menu': 'insideMenuHandler',
        'click':       'outsideMenuHandler'
    }

    insideMenuHandler: function(e) {}, // Called when clicking #menu
    outsideMenuHandler: function(e) {} // Called on every click both on and off #menu

}
Run Code Online (Sandbox Code Playgroud)

作为参考,这是我将单独使用jQuery做的事情:

$(document).click(function(event) {
    if ( $(event.target).closest('#menu').get(0) == null ) {
        $("#menu").slideUp();
    }
});   
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 14

有几件事你需要解决.

首先,如果你的insideMenuHandler回报false或电话,e.stopPropogation()那么你outsideMenuHandler的点击就不会被要求#menu.例如:

http://jsfiddle.net/ambiguous/8GjdS/

但这不是你的全部问题.你outsideMenuHandler只会被要求对你的看法点击; 因此,如果有人点击您视图外的页面,您outsideMenuHandler将无法调用,并且您的菜单也不会停止.如果您希望在有人点击外面的任何地方时菜单关闭#menu,那么您必须手动绑定body并在视图被销毁时手动取消绑定.像这样的东西:

var myView = Backbone.View.extend({
    events: {
        'click #menu': 'insideMenuHandler'
    },

    initialize: function() {
        _.bindAll(this, 'insideMenuHandler', 'outsideMenuHandler');
    },

    render: function() {
        // Both <body> and <html> for paranoia.
        $('body, html').on('click', this.outsideMenuHandler);
        // ...
        return this;
    },

    remove: function() {
        // Clean up after ourselves.
        $('body, html').off('click', this.outsideMenuHandler);
        // ...
    },

    // ...
    outsideMenuHandler: function(e) {
        // ...
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

然后一定要正确删除您的视图.例如:

http://jsfiddle.net/ambiguous/MgkWG/1/