user656925
user656925

Reputation:

Backbone model creation | Conceptual understanding

Can anyone explain how Models are created in Backbone? You pass in an object, but you are able to use new as if it were a function object.

This leads me to believe Backbone is somehow appending the object literal to a function object as you can not do new {key1:value1, key2,value2}

Example from Backbone

var Sidebar = Backbone.Model.extend({
  promptColor: function() {
    var cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

Upvotes: 0

Views: 116

Answers (1)

tkone
tkone

Reputation: 22758

This has to do with how the object system in JavaScript works and the concept of a constructor for an object and the new keyword.

If you define an object with some properties:

var myobj = {
    foo: 'bar'
}

And then try to do new myobj you'll get an error that myobj is not a function.

But, lets say we define a function that sets some passed in value to the this property:

var myobj = function(foo){
    this.foo = foo || "bar";
}

And lets try to make a new instance of that:

var m = new myobj()
m.foo
> bar
var m2 = new myobj('baz');
m2.foo
> baz

This works because functions in JavaScripts are just objects of type function:

typeof myobj
> "function"
typeof myobj.prototype
> "object"

Now, if you look at the Backbone source (specifically line 184) you'll see:

 var Model = Backbone.Model = function(attributes, options) {

That line is saying that a model is actually a function that can accept two arguments, attributes and options.

This is what allows you to create a new copy of this.

Upvotes: 3

Related Questions