9

这段代码没有太多上下文,但会说明我的问题。这是一个在 AMD 模块中定义的主干视图,我使用它通过 require.js 加载

本质上,我希望能够在初始化运行后将事件添加到 Backbone 视图。目前我正在制作一个空的事件对象,然后在一个名为 addView 的方法中,每次调用该函数时都会添加一个事件。这目前不起作用。

我不确定事件是在什么时候注册的,但我怀疑我必须以某种方式让视图在events对象更改时更新它的侦听器?

有人知道我如何在初始化后向 Backbone.js 添加事件吗?

   define([
    'jQuery',
    'Backbone'],

    function ($, Backbone) {

        var contentViews = new Array();

        var SlidePanelView = Backbone.View.extend({

            events: {},

            /// <param name="targetDataAtt">The unique value inside the target's Data-Slide-Panel-Id attribute</param>  
            /// <param name="event">Backbone event to trigger view</param>
            /// <param name="destroyOnRemove">True to destroy view when removed, False otherwise (Default true)</param>  
            addView: function (targetDataAtt, event, view, destroyOnRemove) {
                destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true;

                this.events[event] = "viewEventFired";
                contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove };
            },

            viewEventFired: function (e) {

                var target = $(e.target);
                var id = target.attr('data-slide-panel-id');
                console.log(id);
            }

        });

        // Return a singleton??
        return new SlidePanelView;


    });
4

1 回答 1

11

If I'm understanding the question correctly, after you add additional events to the events hash, call delegateEvents() on the view to re-bind events.

    addView: function (targetDataAtt, event, view, destroyOnRemove) {
       destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true;
       this.events[event] = "viewEventFired";
       this.delegateEvents();
       contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove };
    }

It does unbind all the existing event bindings and rebinds all the events in the events hash again, and I'm not sure of the underlying performance issues of doing that, but its something to be aware of.

于 2012-04-17T02:01:50.670 回答