Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

backbone.js set model array property

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.

question from:https://stackoverflow.com/questions/7325004/backbone-js-set-model-array-property

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...