Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone initialize: function( options ) not working in V9

Tags:

backbone.js

I just upgrade a site I worked on from Backbone.js 0.5.3 to Backbone.js 0.9.2 When I did I get an undefined for my options parameter that I use in my models initialize method. What has changed from V.5 to V.9

initialize: function( options ) {enter code here }

Ok here is my model structure. Everything works fine in 0.5.3 but when I use 0.9.2 options no longer works.

this.myModel = Backbone.Model.extend({

        defaults: function() {
            return {
                maxDays: 7,
                index: 0

            };
        },

        initialize: function( options ) {

        }

})



this.model = new myModel();

In version 0.5.3 options will show all the attributes that were set in the defaults object. but in version 0.9.2 this no longer works it returns undefined. I can not post a link because of the client sensitivity.

like image 254
user1096509 Avatar asked Apr 27 '12 18:04

user1096509


1 Answers

The signature of initialize remains unchanged I believe from 0.5 to 0.9. However, you only get options passed in if you pass them to the constructor. Check out the annotated source for Backbone.Model. Whenever you instantiate a new model instance, the constructor does this:

this.initialize.apply(this, arguments);

So whatever you pass to the constructor gets passed unmodified to initialize. So look in your code for cases where you are instantiating a new model instance but not passing 2 arguments (attributes and options).

Based on your code sample, you now need to define initialize as taking 2 parameters: attributes and options and when creating your models, if you want to just pass options do:

var model = new Model(null, options);

or

var model = new Model({}, options);

I think the specific change that broke your code is the switch from calling initialize with explicit arguments in 0.5.3 to using apply and arguments in 0.9.3 like this:

    this.initialize.apply(this, arguments);

So in 0.9 you can get access to your defaults through this.attributes, but they won't come in as a function parameter unless they came in as a parameter to the constructor function.

var MyModel = Backbone.Model.extend({
    defaults: {x: 42, y: 43},
    initialize: function(attributes, options) {
        console.log(arguments, attributes, this.attributes);}
});
var m = new MyModel();

That will log [], undefined, Object since arguments is empty, attributes is undefined since nothing was passed to the constructor, but the defaults HAVE been set in this.attributes and are there for you to use.

like image 97
Peter Lyons Avatar answered Oct 08 '22 21:10

Peter Lyons