【问题标题】:Backbone custom event trigger not being recognised?无法识别主干自定义事件触发器?
【发布时间】:2012-07-28 13:06:47
【问题描述】:

我是第一次学习 Backbone.js,但在尝试从触发(或从视图中识别何时触发)获取自定义事件时遇到问题?

您可以在此处查看我的集合代码:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86,它在初始化时会触发自定义 collection:init 事件。

var Contacts = Backbone.Collection.extend({
    model: Contact,

    initialize: function(){
        this.trigger('collection:init');
        this.bind('add', this.model_added, this);
    },

    model_added: function(){
        console.log('A new model has been created so trigger an event for the View to update the <select> menu');
    }
});

但稍后在我正在监听该事件的视图中,我无法让函数 populate 触发:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L90-107

var ContactsView = Backbone.View.extend({
    initialize: function(){
        console.log(contacts.models, 'get initial model data and populate the select menu?');
    },

    events: {
        'collection:init': 'populate',
        'change select': 'displaySelected'
    },

    populate: function(){
        console.log('populate the <select> with initial Model data');
    },

    displaySelected: function (event) {
        console.log('get model data and display selected user', event);
    }
});

任何想法我做错了什么?

【问题讨论】:

  • 嗨,视图是否通过构造函数接收集合?在视图内部的初始化方法期间,您是否订阅了这样的事件this.collection.on("init",this.populate)

标签: backbone.js


【解决方案1】:

视图中的事件哈希用于将事件从 DOM 绑定到您的视图,例如渲染视图中的元素引发的事件。要收听您的收藏引发的事件,您必须手动设置它们:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        contacts.on("collection:init",this.populate,this);
    }
    ...
});

请注意,您使用的是全局联系人变量,我建议您使用 Backbone 机制并将您的集合传递给构造函数,就像使用 el 一样:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        console.log(this.collection.models);
        this.collection.on("collection:init",this.populate,this);
    }
    ...
});

var contacts_view = new ContactsView({
    el: $('#view-contacts'),
    collection:contacts
});

正如@mu 在 cmets 中所说,您的事件不会做任何事情,因为您在集合的初始化方法中触发它,该方法由集合的构造函数自动调用,因此在您可以绑定任何内容之前风景。请参阅此 Fiddle 以可视化调用顺序:http://jsfiddle.net/yRuCN/

在别处触发它,或者,如果我没看错你的意图,你(可能)想要使用内置的重置事件:

var ContactsView = Backbone.View.extend({
    initialize: function(){
        this.collection.on("reset",this.populate,this);
    }
    ...
});

有关潜在用途的示例,请参见 http://jsfiddle.net/yRuCN/1/

【讨论】:

  • this.collection.on("collection:init",this.populate,this); 还是会有问题的,不是吗?在任何东西可以绑定到该事件之前,集合总是会被初始化(并触发"collection:init")。
  • @mu 你完全正确,我不知道如何解释,这就是为什么我添加了关于重置事件的提及。我会以某种方式编辑我的答案并添加您的评论:)
  • 我认为您对重置事件的看法是正确的。 model_added 也应该在视图上。
  • @Integralist 这就是 Mu 和我在之前的 cmets 中讨论的内容,在 initialize 方法中触发事件不会让你到任何地方,因为 initialize 是构造函数的一部分,所以什么都听不到它。检查我刚刚添加的第一个 Fiddle,看看创建集合时会发生什么。第二个小提琴应该为您指明潜在解决方案的方向。
  • @Integralist 和最后一个小提琴来演示自定义事件jsfiddle.net/yRuCN/2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多