First of all, I did some search and no answer on stackoverflow/google provided me the thing I wanted.
Here’s a snippet of my code:
//in the view
this.collection.on("add",triggerthis)
this.collection.add(predefinedModel)
triggerthis: function(a, b, c, d){
//etc.
}
Basically, I want to be able to pass an argument on add and receive the argument in triggerthis. Is this possible?
Thanks in advance.
You can’t do this the way you want without using undocumented features.
If we have a look at
Collection#add, we’ll see this:Note the fourth argument to
trigger. And if we look at the documented interface fortrigger:So the
addwill call the listeners asf(model, collection, options)whereoptionsis the sameoptionswhat you passed toCollection#add. The result is that if you do this:then you could do this in your callback:
Demo: http://jsfiddle.net/ambiguous/bqWwQ/
You could of course tunnel a whole array or object through
optionsthis way.The third argument for
"add"events isn’t documented (at least not that I can find), the closest thing to documentation for this is a note in the 0.3.3 Changelog entry:I wouldn’t recommend this approach but it is there if you need it; you will of course need to cover this in your test suite and you’ll need to make sure you don’t use any keys in
optionsthat Backbone will be using.A safer approach would be to attach some extra properties to the model:
and then peel that off in the callback:
Demo: http://jsfiddle.net/ambiguous/M3UaH/
You could also use different callbacks for different purposes or pass your extra parameters as full blown model attributes.
There’s also
_.bind:but that will bind arguments from left to right so you’ll have to specify all the arguments that your callback will need.
Demo: http://jsfiddle.net/ambiguous/jUpJz/