I'm new to JS and Backbone
What's the difference between these two?
TestModel = new Backbone.Model({ title: "test title" })
TestModel = Backbone.Model.extend({ title: "test title" })
There is a basic difference, which in short can be described as "the difference between the project of a house and the house itself".
For expert programmers I would just say that "new Backbone.Model" returns an object instance, but "Backbone.Model.extend" returns a constructor function
FIRST: a new object (i.e. The house)
var TestModel = new Backbone.Model({ title: "test title" });
you create a new Object whose structure (methods and variables) have been defined somewhere else. Object can be considered as "all the non-native items" of a language, where for "native item" I mean basic types like integers, characters etc.
In the braces {} you pass the value of some variable or method. This is called, as Tomasz Nurkiewicz previously explained, a constructor, because it allows you to 'construct' a new object whose model has been described elsewhere.
To give you a known example: you write
var myArray = new Array();
It means that you are creating a new Array, which is a non-native object which has been defined elsewhere. you can also write:
var myArray = new Array([1,2,3,4,5]);
And it fills the array with the given numbers.
SECOND: modify definition of an existing object (i.e. The project of the house)
with
var TestModel = Backbone.Model.extend({ title: "test title" })
you say something very simple to your VM: "the object you give me as default is very nice, but I want to implement more functions/properties". So with the "extend" clause you modify the definition of an object adding or override existing method/properties.
Example: a nice example in backbone.js is given by the comparator function of a collection. When you extend the object defining it, "it will be used to maintain the collection in sorted order".
Example:
myCollection = Backbone.Collection.extend({
comparator:function(){
return item.get('name');
}
});
IN GENERAL
What you are expected to do when 'backboning' (developing using backbone.js framework) is to extend the given object (for instance a View) with:
window.ButtonView = Backbone.View.extend({
btnText:'nothingByDefault',
myNewMethod:function(){
//do whatever you want, maybe do something triggered by an event, for instance
}
});
and then use it somewhere else in the code, once for each button you want to handle, including in the braces all the values you want to give to the object
[...]
var submitBtn = new ButtonView({btnText:"SubmitMe!"}),
var cancelBtn = new ButtonView({btnText:"Erase All!"});
....Hope this helps...