Backbone.js 设置模型数组属性 [英] backbone.js set model array property

查看:21
本文介绍了Backbone.js 设置模型数组属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数组作为属性的bac​​kbone.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.

推荐答案

您尝试的语法不起作用,因为发送到 set 方法的参数是对象字面量.: 左侧的值被视为文字名称,而右侧的值可以执行/解释代码.

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.

另一种方法是使用 get 来缩短流程,并直接更新数组:

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]

这里的缺点是这不会触发更改"事件,因为您没有调用 set 方法.所以,如果你需要这些事件,你必须自己触发它们,正如我所展示的.

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.

这篇关于Backbone.js 设置模型数组属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆