Trunk: how the trigger function works

I am trying to learn Backbone by looking at an application that I know was made along with the basic documentation. The application has a Bucket model and a company model (i.e. you put companies in a bucket). There is one thing in this bit that I don’t understand about, namely how it uses the method trigger.

The documentation for the base station says trigger:

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

Trigger callbacks for a given event or a list of events separated by spaces. Subsequent arguments to trigger will be passed along with the event callbacks.

In the code I'm viewing, it triggeris called like this:

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

Two questions:

  • eventI assume the addcompany, but at what point in the code below does this really happen? Is it when executed this.set({ "companies": arr }, { silent: true });or when executed this.save();(or something else)?

  • If Companies.get(companyId)- an optional argument, what function did he actually pass?

Source code excerpt

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

  // ...
+3
source share
1 answer

The companiesbucket property is updated in the method you describe addCompany. An annotated version of your example shows what happens:

  // 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 company list with the array,
  //    suppressing validation and events:
  this.set({"companies": arr}, {silent: true});

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

triggerdoesn't really affect the model - it's just a way to let other parts of the application know that the company has been added. You can turn around and catch him elsewhere using onwith 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.');
});
+8
source

All Articles