Backbone: how the trigger function works
backbone.js, callback, events
Solution
The `companies` property of the bucket is being updated in the `addCompany` method you describe. An annotated version of your example shows what's taking place:
// 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` isn'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 using `on` with the bucket model:
var bucket = new window.Bucket();
// do stuff
bucket.on('add:companies', function(company) {
alert('a new company has been added to the bucket.');
});
Problem
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 `event` I assume is `add`ing a company, but at what point in the code below does that actually happen? Is it when `this.set({ "companies": arr }, { silent: true });` is run or when `this.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)); }, // ... ```