Backbone.js的设定模型内部属性直接哈希 [英] backbone.js set model internal attributes hash directly
问题描述
使用Backbone.js的我知道这是强烈建议使用设置的方法来设置一个模型的属性,不是通过直接修改属性href=\"http://documentcloud.github.com/backbone/#Model-attributes\">内部哈希的 然而,除了没有触发自动改变事件中直接修改内部哈希什么其他的缺点或副作用有哪些? 我现在面临的问题是,虽然set方法接受一个对象文本,我需要使用在运行时确定的变量左侧分配。谢谢你。
myModel.set({
myProperty的:myvalue的; // myProperty的是一个变量,所以这是无效的语法
})// VSmyModel.attributes [myProperty的] = myvalue的; // myProperty的是,可以评价的可变
好吧,如果你看的注明出处code ,你会发现,设置
做了很多。
如果你扩展Backbone.Model有一个功能,它会为你:
Backbone.Model.prototype.setByName =功能(键,值,选项){
VAR二传手= {};
二传手[关键] =价值;
this.set(二传手,期权);
};
然后,你可以做要直接在模型上的内容:
VAR模型=新Backbone.Model();
model.setByName(myProperty的巴);
这感觉就像一个更好的解决方案给我。
修改
作为@ earl3s指出,这已不再是较新版本的骨干必要的。今天,你可以叫 model.set(myProperty的栏)
和它你想要做什么。
Using Backbone.js I know it's highly recommended to set a model's property using the set method, and NOT by directly modifying the attributes internal hash.
However, apart from not firing the "change" event automatically, what other cons or "side-effects" are there in modifying the internal hash directly?
The problem I'm facing is that while the set method takes an object literal, I need to assign the left hand side using a variable determined at run-time. Thanks.
myModel.set({
myProperty : myValue; //myProperty is a variable, so this is invalid syntax
})
//vs
myModel.attributes[myProperty] = myValue; //myProperty is a variable that can be evaluated
Well, if you look at the annotated source code, you'll find that set
does a lot.
What if you extended Backbone.Model with a function that does it for you:
Backbone.Model.prototype.setByName = function(key, value, options) {
var setter = {};
setter[key] = value;
this.set(setter, options);
};
Then, you can just do what you want directly on the model:
var model = new Backbone.Model();
model.setByName(myProperty, "bar");
That feels like a better solution to me.
Edit
As @earl3s pointed out, this is no longer necessary in more recent versions of Backbone. Today, you can just call model.set(myProperty, "bar")
and it does what you want.
这篇关于Backbone.js的设定模型内部属性直接哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!