I’m trying to learn Backbone by looking at an app that someone I know made together with the backbone documentation. The app has a Bucket model and a Company model (i.e. you put companies in the bucket). There’s one thing in this bit that I’m unclear about, namely, how it uses the trigger method.
Backbone documentation has this to say about trigger:
trigger object.trigger(event, [*args])
Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.
In the code I’m looking at, trigger is called like this:
this.trigger("add:companies", Companies.get(companyId));
Two questions:
-
The
eventI assume isadding a company, but at what point in the code below does that actually happen? Is it whenthis.set({ "companies": arr }, { silent: true });is run or whenthis.save();is run (or something else)? -
If
Companies.get(companyId)is the optional argument, what function is it actually passed to?
Excerpt from original code
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));
},
// ...
The
companiesproperty of the bucket is being updated in theaddCompanymethod you describe. An annotated version of your example shows what’s taking place:triggerisn’t actually affecting the model–it’s just a way of letting other pieces of the application know that the company has been added. You could turn around and catch it somewhere else usingonwith the bucket model: