Backbone:触发器功能如何工作

时间:2012-04-15 02:39:45

标签: events backbone.js callback

我正在尝试通过查看我认识的人与骨干文档一起制作的应用程序来学习Backbone。该应用程序具有Bucket模型和公司模型(即您将公司放入存储桶中)。这一点有一点我不清楚,即它如何使用trigger方法。

Backbone文档可以说明trigger

触发object.trigger(event, [*args])

  

触发给定事件或以空格分隔的事件列表的回调。触发器的后续参数将传递给事件回调。

在我看到的代码中,trigger被称为:

this.trigger("add:companies", Companies.get(companyId));

两个问题:

  1. 我认为eventadd公司,但在下面的代码中,实际发生了什么?是运行this.set({ "companies": arr }, { silent: true });还是运行this.save();时(或其他)?

  2. 如果Companies.get(companyId)是可选参数,它实际传递给哪个函数?

  3. 摘自原始代码

    window.Bucket = Backbone.Model.extend({
      defaults: function() {
        return {
          companies: []
        };
      },
    
      addCompany: function(companyId) {
        var arr = this.get("companies");
        arr.push(companyId);
        this.set({ "companies": arr }, { silent: true });
        this.save();
        this.trigger("add:companies", Companies.get(companyId));
      },
    
      // ...
    

1 个答案:

答案 0 :(得分:8)

正在使用您描述的companies方法更新存储区的addCompany属性。您的示例的带注释版本显示正在发生的事情:

  // 1. get array of companies currently included in the bucket:
  var arr = this.get("companies");

  // 2. add a company to the array
  arr.push(companyId);

  // 3. replace the bucket's company list with the array,
  //    suppressing validation and events:
  this.set({"companies": arr}, {silent: true});

  // 4. save the bucket:
  this.save();

trigger实际上并没有影响模型 - 它只是让应用程序的其他部分知道已添加公司的一种方式。您可以使用on使用存储桶模型转向并将其捕获到其他位置:

var bucket = new window.Bucket();

// do stuff

bucket.on('add:companies', function(company) {
  alert('a new company has been added to the bucket.');
});
相关问题