2

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that is logic, but my question is, how to make in in cycle: I mean if i have string with key and string with value, how i can make it using .set()? For ex. this code not work: var key = 'country', value = 'some value'; model.set({key, value});
i changed my answer with what you need to insert the changes. actually they are set as one object, you don't need to loop and set, but you do need a loop to create the object :s
var attrs = {}; attrs[key] = value; model.set(attrs);
Yes thats true =) Big thanks for you Sander and maxl0rd That is what I mean, now it works perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.