sdespolit
sdespolit

Reputation: 913

class constructor with backbone

task

to make it possible to pass named paramteres to new bb-backed objects

example

initialize : function(foo, bar, baz){
  this.foo = foo;
  ...
}


new Foo(value0, value1, value2)

question

Is it possible without modifying the library source code?

Upvotes: 0

Views: 165

Answers (2)

mu is too short
mu is too short

Reputation: 434615

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 and arguments 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.

Upvotes: 2

Andreas Köberle
Andreas Köberle

Reputation: 110892

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

Upvotes: 0

Related Questions