Lea*_*cim 4 events callback backbone.js
我正在尝试通过查看我认识的人与骨干文档一起制作的应用程序来学习Backbone.该应用程序有一个Bucket模型和一个公司模型(即你把公司放在桶中).这一点有一点我不清楚,即它如何使用该trigger方法.
Backbone文档有这样的说法trigger:
object.trigger(event, [*args])触发给定事件或空格分隔的事件列表的回调.触发器的后续参数将传递给事件回调.
在我看的代码中,trigger被称为:
this.trigger("add:companies", Companies.get(companyId));
Run Code Online (Sandbox Code Playgroud)
两个问题:
在event我认为是add荷兰国际集团一公司,但在代码中的什么点以下不会实际发生的呢?是this.set({ "companies": arr }, { silent: true });运行时this.save();还是运行时(或其他)?
如果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));
},
// ...
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
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.');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24645 次 |
| 最近记录: |