Fijjit
Fijjit

Reputation: 1467

Most efficient way of adding functions to a Backbone Model

To add a function to a Backbone Model, I can do one of two things:

App.WidgetModel= Backbone.Model.extend({
    sayHello: function(){
        console.log('Hello, I'm a widget');
    }
});

...or...

App.WidgetModel = Backbone.Model.extend({});

App.WidgetModel.prototype.sayHello = function(){
    console.log('Hello, I'm a widget');
};

Which is the 'right' way of doing this if I will have thousands of widgets in my app at any time?

Upvotes: 0

Views: 47

Answers (1)

pdjota
pdjota

Reputation: 3243

Usually the first is more common than the second.

App.WidgetModel= Backbone.Model.extend({
    sayHello: function(){
        console.log('Hello, I\'m a widget');
    }
});
App.SomeotherModel = App.Widget.extend({
  sayHello: function () {
    App.Widget.call(this);
    console.log('Hello, I\'m a SomeotherModel');
  };
});

Even though you may want to extend a model with things that are not backbone

var someObject = {/**/};
_.extend(someObject, App.SomeotherModel); 

Look for instance at http://backbonejs.org/#Events

If we look at the source the .extend method does some other things like fixing the prototype chain for the surrogate models so if you are going to use Model2 = Model1.extend and so on it is better to define the methods with extend.

Upvotes: 2

Related Questions