Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js set model array property

Tags:

backbone.js

I have a backbone.js model with an array as a property:

defaults: {
    myArray : [0,1,2]
}

I'm trying to set the value for a particular index.

var myIndex = 1;
myModel.set({"myArray"[myIndex] : newVal}); //doesn't work
myModel.set({"myArray[myIndex]": newVal}); //doesn't work
myModel.set({"myArray" + "[" + myIndex + "]": newVal}); //doesn't work

What's the proper syntax to get/set array properties? Thanks.

like image 685
fortuneRice Avatar asked Sep 06 '11 19:09

fortuneRice


2 Answers

the syntax you're trying doesn't work because the parameters sent into the set method are an object literal. the values on the left side of the : are treated as literal names, while the values on the right can be executed / interpreted code.

there's a few things you can do, though:

get, update, and set the entire array:

var a = myModel.get("myArray");
a[0] = 5
myModel.set("myArray", a);

myModel.get("myArray"); //=> [5, 1, 2]

the advantage in doing it this way is that you get the standard "change" events fired from the model because you are setting the value of the attribute on the model.

another way to do it would be to shortcut the process by using a get, and updating the array directly:

myModel.get("myArray")[0] = 5
myModel.trigger("change");
myModel.trigger("change:myArray");

myModel.get("myArray"); //=> [5, 1, 2]

the disadvantage here is that this won't fire the "change" events because you're not calling the set method. so, if you need those events, you have to fire them yourself, as i've shown.

like image 63
Derick Bailey Avatar answered Oct 06 '22 02:10

Derick Bailey


Derick's answer is mostly correct aside from one thing. Getting and then setting an array property will not generate the change events on the model.

The get call gives you a reference to the array in the "myArray" property, which you then modify. Because you have a reference to an object, you're directly modifying the same array as on your model. When you then call "set," the object you're passing is exactly equal to the array for that property (because they are both references to the same object), and no change is detected because there is no change in the set operation.

To trigger a change event, you either still have to call it manually (as in Derick's second example), or create a clone of the array and use that in your setter (since it is now a completely different object).

like image 21
Ian Garrison Avatar answered Oct 06 '22 01:10

Ian Garrison