0

I need to add a function for all my models, but I can“t do how to recognize the model as "this" scope variable. My function will do my model can be reseted to the defaults and by some data-object as parameter:

Backbone.Model.prototype.reset = function( data ){

        this.set(this.defaults);

        $.each( data, function( key, value ){

              this.set( key, value );
        });
}
Brian
  • 349
  • 1
  • 5
  • 16

2 Answers2

4

Your code seems legit. the value of this is defined at runtime and depends on how you call your method. if you will use modelInstance.reset() the value of this will be modelInstance.

However, mutating the prototype of a 3rd party is considered a bad practice that should be avoided. A better practice is to create an abstract model and have all of your model implement it.

It will look something like:

var AbstracrtModel = Backbone.Model.extend({
  reset: function (data, options) {
    this.clear(options);
    this.set(_.defaults({}, data || {}, this.defaults || {}), options);
  }
});

The api of model.set permits passing a data hash, so you don't really need the inner loop.

u.k
  • 3,091
  • 1
  • 20
  • 23
2

Your "this" context inside the $.each is the iterator. You could get a

var self = this;
$.each( data, function( key, value ){
    self.set( key, value );
});

And the use self inside the each function, or bind the context to the function.

$.each( data, function( key, value ){
    this.set( key, value );
}.bind(this));
Juan Pablo
  • 363
  • 2
  • 9