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

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

问题描述

我对Backbone.js的一个简单的问题获取设置功能。

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

1)与下面的code,我怎么能'获取'或'设置'obj1.myAttribute1直接?

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

另一个问题是:

2)在模型中,除了在默认对象,其中可以/我应该声明我的模型的其他属性,这样,他们可以通过骨干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?
    }
});

我知道我可以做的:

I know I can do:

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

但是,好的做法呢?

but is that good practice?

推荐答案

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 ,如更改事件或验证。

有一个更好的解决办法是永远窝在POJSOs你的模型(普通的旧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());
    }
});

然后访问code将

Then the accessing code would be

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

但更重要的是设置code将

but more importantly the setting code would be

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

这将会触发相应的改变事件等等。例如,工作在这里: http://jsfiddle.net/g3U7j/

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

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