How to change default model attributes using set method in Backbone.js

10,561

try the .set() function...

appState.set({arg : val});

once you set the arguments using .set() it will override the default for that.

your example modified a bit:

window.AppState = Backbone.Model.extend({
  defaults: function() {
    return {
      country:  false,
      region: false
    };
  }
});

var appState = new AppState();

// when you get your array of new values you can turn it in an object
var myArray = [["country", "new country value"], ["region", "new region value"]];
var newValues = {};
for (var i = 0; i < myArray.length; ++i)
{
    newValues[myArray[i][0]] = myArray[i][1];
}

// set the properties to the new values
appState.set(newValues);

// if you now return the json of the model, it has changed properties
console.log(appState.toJSON());

remark this for loop depends a lot on the structure of your array, the way i wrote it will work for the array you gave in your example, should anything change to that you will need to change the working of the for loop

remark 2 if you use this technique more often, you could always extract that functionality in a helper method.

Share:
10,561
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I have some defults data in Model

    window.AppState = Backbone.Model.extend({
      defaults: function() {
        return {
          country:  false,
          region: false
        };
      }
    });
    
    var appState = new AppState();
    

    Then in Router I get array with new values for model like this:

    [["country", "new country value"], ["region", "new region value"]]
    

    And now in a for loop i cycle to update all received params... I realize it this way

    appState.attributes[arg] = val;
    

    but I think it's not clear, because in documentation of Backbone.js I read about "attribute" method and see this: "Please use set to update the attributes instead of modifying them directly." So my questions is: How i can change attributes of defaults using set method?