to make it possible to pass named paramteres to new bb-backed objects
initialize : function(foo, bar, baz){
this.foo = foo;
...
}
new Foo(value0, value1, value2)
Is it possible without modifying the library source code?
If you check the source you'll see that Model calls initialize
like this:
Backbone.Model = function(attributes, options) {
// ...
this.initialize(attributes, options);
};
But Collection, Router, and View call it like this:
this.initialize.apply(this, arguments);
And as we all know, apply
does this:
Calls a function with a given
this
value andarguments
provided as an array.
and arguments
is:
An array-like object corresponding to the arguments passed to a function.
So for models you're stuck with the standard documented interface but for the rest you can do things like this:
var View = Backbone.View.extend({
initialize: function(a, b, c, d) {
// ...
}
});
new View('where', 'is', 'pancakes', 'house?');
Demo: http://jsfiddle.net/ambiguous/5ZD6z/
Note that doing this violates the documented Collection , Router , and View interfaces so don't be surprised if using this undocumented behavior causes new and interesting bugs or breaks mysteriously after an upgrade. I'd recommend sticking to the documented interfaces and if it really bothers you so much, write constructor functions:
function make_thing(a, b c) {
return new Thing({
a: a,
b: b,
c: c
});
}
and move on to more productive things.
You can pass JavaScript objects as parameters into the constructor, take a look at the docu for Model.extend :
MyModel = Backbobe.Model.extend({
initialize: function(options){
this.foo = options.foo;
}
});
//pass your options as second parameter in the constructor call
// the first parameter is used as your model data
var myModel = new MyModel({},{foo:bar});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.