Unbreakable
Unbreakable

Reputation: 8132

Initialize Model elements in javascript/backbone

I am getting a nested JSON data from REST. Now I want to capture that value in a variable. Everything is working fine but I don't know how should I initialize that variable.

So here is my initialize method of Model.

initialize: function() {
        var self = this;
        if (!this.get('dropdownData')) {
                this.set({
                    dropdownData: []
                });
            }
        }
}

AJAX CALL:

fetchDropdown: function(data) {
            var self = this;
            var d = $.Deferred();
            var dropdownRequest = $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: this.urlRoot,
                data: JSON.stringify(data)
            });
            dropdownRequest.done(function(data)
            {
                self.set({
                            dropdownData: data
                        });
                console.log("JSON SUCCESS!! YAY!!");
                d.resolve();

            });

Now dropdownData should be initialized as dropdownData: {} or dropdownData: [] or I don't need to initialize it at all.

P.S: Logic wise code snippet is working. I just want to know what's the correct way to initialize the dropdownData in the initializefunction in BACKBONE MODEL

Upvotes: 0

Views: 311

Answers (1)

Lochlan
Lochlan

Reputation: 2796

I would recommend avoiding initializing dropdownData in the initialize method entirely, instead utilizing model.defaults here. If you add the following to your model definition:

defaults: function () {
  return {
    dropdownData: []
  };
},

...then you can remove all the code in the body of your initialize method. The result of this change will be that an instantiated model will either have the supplied value (at instantiation) for dropdownData or the model will default to the empty array specified.

Note that it's important to use the function version of defaults here. If you were to do this instead:

defaults: {
  dropdownData: []
},

...then any instantiated model not supplied with a value for dropdownData would share a value for dropdownData. Every instance would refer to the exact same array.

Upvotes: 1

Related Questions