4

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

骨干文档有这样的说法trigger

扳机object.trigger(event, [*args])

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

在我正在查看的代码中,trigger这样调用:

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

两个问题:

  1. event假设是add一家公司,但在下面的代码中,这实际上是在什么时候发生的?是什么时候this.set({ "companies": arr }, { silent: true });运行还是什么时候this.save();运行(或其他)?

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

摘自原始代码

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));
  },

  // ...
4

1 回答 1

9

存储桶的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.');
});
于 2012-04-15T02:45:31.987 回答