0

我正在编写一个带有三个类似子布局的木偶布局。它们中的每一个都是同一个类的一个实例。这是代码:

Marionette.Layout.extend({
        subCollection1: new SubCollection(),
        subCollection2: new SubCollection(),
        subCollection3: new SubCollection(),

        initialize: function () {
            this.subView1 = new subView ({
                collection: this.subCollection1)
            });
            this.subView2 = new subView ({
                collection: this.subCollection2)
            });
            this.subView1 = new subView ({
                collection: this.subCollection3)
            });
        },

        onRender: function() {
            this.Reg1.show(this.subView1);
            this.Reg2.show(this.subView2);
            this.Reg3.show(this.subView3);
        },

        fetchColletions: function () {
            this.subCollection1.fetch({ data: { /* some data for webserver */ } });
            this.subCollection2.fetch({ data: { /* some data for webserver */ } });
            this.subCollection3.fetch({ data: { /* some data for webserver */ } });
        }
});

然后在我的 subLayout 中,我将函数绑定到初始化函数中的集合请求,如下所示:

Marionette.Layout.extend({
        onCollectionRequest: function () {
            console.log('summary.onCollectionRequest ' + this.cid);
            //debugger;
        },

        initialize: function () {
            this.listenTo(this.collection, 'request', this.onCollectionRequest);

        }
    });

问题是,对这些集合中的任何一个调用 fetch 都会触发所有三个集合中的请求事件,所以我得到这样的日志:

fetchcollections
GET /* 服务器地址 */ 200 OK 157ms
onCollectionRequest view15
onCollectionRequest view24
onCollectionRequest view33
GET /* 服务器地址 */ 200 OK 332ms
onCollectionRequest view15
onCollectionRequest view24
onCollectionRequest view33
/* 第三个以此类推 */

我错过了什么吗?我一直认为事件绑定是每个实例而不是每个类。我应该如何解决这个问题?

PS我的代码另外包含在require.js中define(),但我认为这与我的问题无关,所以我在代码片段中省略了它。

4

1 回答 1

0

嗯,我已经解决了我的问题。事实证明,我在我的 App 初始化程序中做了一件非常糟糕的事情。为了获得全局获取错误处理程序,我在原型上使用了“on”函数:

Backbone.Collection.prototype.on('error', fetchErrorHandler);

正如如何向所有 Backbone 模型添加默认错误处理程序?这是一个坏主意,因为它为应用程序中的所有集合实例创建全局事件处理程序。它导致每个事件处理程序对于所有集合都是通用的,这正是我的问题。

于 2013-10-29T09:19:38.513 回答