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

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

问题描述

我有一个数组作为属性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.

推荐答案

你想不工作,因为发送到设置方法的参数是一个对象字面量的语法。在左侧的值:被视为文本名称,而在右边的值可以被执行/帧间preTED code

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]

这里的缺点是,因为你没有调用设置方法,这将不火的变事件。所以,如果你需要这些事件,你必须自己解雇他们,因为我已经展示。

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天全站免登陆