【问题标题】:Backbone pass object with event带有事件的主干通道对象
【发布时间】:2014-02-13 16:41:09
【问题描述】:

阅读 Backbone 的教程,似乎当从 collection 触发 add 事件时,添加的项目与事件一起发送(remove 也是如此)。我在backbonejs.org 站点上找不到有关此功能的任何文档,并且很好奇是否有一种方法可以将对象与我的自定义events 一起发送。其次,Marionette 中是否有可能发生这样的事情?

【问题讨论】:

    标签: events backbone.js marionette backbone-events


    【解决方案1】:

    Backbone 定义的每个对象都混合在Backbone.Events 中,这意味着您可以使用object.trigger 触发事件。它被定义为

    触发器 object.trigger(event, [*args])
    触发给定事件或以空格分隔的事件列表的回调。随后的论点 to trigger 将被传递给事件回调。

    您只需传递其他参数即可在回调中获取它们。

    例如,

    var m = new Backbone.Model();
    m.on('custom', function(more) {
         console.log(more);
    });
    m.trigger('custom', 'more info');
    

    将记录more info

    请参阅http://jsfiddle.net/nikoshr/HpwXe/ 以获取演示

    你会触发一个引用对象的事件来模拟主干的行为:

    var m = new Backbone.Model();
    m.on('custom', function(model, more) {
         console.log(arguments);
    });
    m.trigger('custom', m, 'more info');
    

    http://jsfiddle.net/nikoshr/HpwXe/1/

    在派生模型中:

    var M = Backbone.Model.extend({
        custom: function() {
            this.trigger('custom', this);
        }
    });
    
    var m = new M();
    m.on('custom', function(model, more) {
         console.log(model);
    });
    m.custom();
    

    http://jsfiddle.net/nikoshr/HpwXe/2/

    【讨论】:

      【解决方案2】:

      当然可以,你可以使用 Backbone.Event

      var collection = Backbone.Collection.extend();
      collection = new collection();
      collection.on("message", function(message){
        console.log(message);
      });
      
      var model = new Backbone.Model();
      collection.add(model);
      model.trigger("message", "This is message");
      

      关于骨干网documentation可以看到哪些类型的事件。

      这是demo

      您也可以使用 Marionette.js 中的 Event Aggregator

      事件聚合器实现。它从 Backbone.Events 扩展,在对象中提供核心事件处理代码,该对象本身可以根据需要进行扩展和实例化。

      var vent = new Backbone.Wreqr.EventAggregator();
      
      vent.on("foo", function(){
        console.log("foo event");
      });
      
      vent.trigger("foo");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-10
        相关资源
        最近更新 更多