Backbone add event

2019-06-17 01:30发布

问题:

I have a collection where is has an event that gets fired when a model is added. I have read in the docs where it should have an options parameter but not able to get to it. I basically want to find the index the model is at in the collection. Inside my collection I have this.

    initialize: function( ) {
        this.bind( 'add', this.onModelAddedd, this );
    },

    onModelAddedd: function( model, options ){

           console.log("options = ", options);
    }

回答1:

The documentation is a little unclear on this so your confusion is understandable. From the fine manual:

Catalog of Events

Here's a list of all of the built-in events that Backbone.js can fire. You're also free to trigger your own events on Models and Views as you see fit.

  • "add" (model, collection, options) — when a model is added to a collection.
  • ...

So the second argument to the add handler is the collection itself. The ubiquitous options that you're looking for is always the last argument so you want this:

onModelAddedd: function(model, collection, options) {
    console.log("options = ", options);
}

Demo (open your console please): http://jsfiddle.net/ambiguous/Das2t/

The final options argument is implied to be the last argument throughout the documentation but it isn't explicitly spelled out anywhere.



标签: backbone.js