Backbone.js 获取和设置嵌套对象属性 [英] Backbone.js get and set nested object attribute

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

问题描述

我有一个关于 Backbone.js 的 getset 函数的简单问题.

I have a simple question about Backbone.js' get and set functions.

1) 使用下面的代码,我如何直接获取"或设置"obj1.myAttribute1?

1) With the code below, how can I 'get' or 'set' obj1.myAttribute1 directly?

另一个问题:

2) 在模型中,除了 defaults 对象之外,我可以/应该在哪里声明模型的其他属性,以便可以通过 Backbone 的 get 和 set 方法访问它们?

2) In the Model, aside from the defaults object, where can/should I declare my model's other attributes, such that they can be accessed via Backbone's get and set methods?

var MyModel = Backbone.Model.extend({
    defaults: {
        obj1 : {
            "myAttribute1" : false,
            "myAttribute2" : true,
        }
    }
})

var MyView = Backbone.View.extend({
    myFunc: function(){
        console.log(this.model.get("obj1"));
        //returns the obj1 object
        //but how do I get obj1.myAttribute1 directly so that it returns false?
    }
});

我知道我能做到:

this.model.get("obj1").myAttribute1;

但这是好的做法吗?

推荐答案

虽然 this.model.get("obj1").myAttribute1 很好,但它有点问题,因为那样你可能会受到诱惑为集合做同样类型的事情,即

While this.model.get("obj1").myAttribute1 is fine, it's a bit problematic because then you might be tempted to do the same type of thing for set, i.e.

this.model.get("obj1").myAttribute1 = true;

但如果您这样做,您将无法获得 myAttribute1 的 Backbone 模型的好处,例如更改事件或验证.

But if you do this, you won't get the benefits of Backbone models for myAttribute1, like change events or validation.

更好的解决方案是永远不要在模型中嵌套 POJSO(纯旧 JavaScript 对象"),而是嵌套自定义模型类.所以它看起来像这样:

A better solution would be to never nest POJSOs ("plain old JavaScript objects") in your models, and instead nest custom model classes. So it would look something like this:

var Obj = Backbone.Model.extend({
    defaults: {
        myAttribute1: false,
        myAttribute2: true
    }
});

var MyModel = Backbone.Model.extend({
    initialize: function () {
        this.set("obj1", new Obj());
    }
});

然后访问代码将是

var x = this.model.get("obj1").get("myAttribute1");

但更重要的是设置代码是

but more importantly the setting code would be

this.model.get("obj1").set({ myAttribute1: true });

将触发适当的更改事件等.这里的工作示例:http://jsfiddle.net/g3U7j/

which will fire appropriate change events and the like. Working example here: http://jsfiddle.net/g3U7j/

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

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