3

有没有办法在 Backbone.js 中构建更复杂的模型,让我通过一个例子来解释:

这是一个 Json 会话对象:

{
    id: "17",
    notes: "",
    start: "2012-10-18T15:57:41.511Z",
    end: "2012-10-18T19:22:31.875Z",
    sessionType: {
        id: "1",
        name: "Life Style",
    }
}

从服务器检索 Session 对象时,我想要一个 SessionType Backbone.Model 以便在该对象周围添加一些业务逻辑。

到目前为止,我只能检索具有虚拟 SessionType 的对象会话,我无法在其上添加任何逻辑,因为它不属于任何 Backbone 模型。

4

2 回答 2

3

You can try this:

window.SessionType = Backbone.Model.extend({

    initialize:function () {
    },

});

Then in your session model, have a method:

window.Session = Backbone.Model.extend({

    initialize:function () {
    },

    getSessionType () {
        return new SessionType(this.get('sessionType'));
    }

});

Now you can call the getSessionType() method which returns a model that can have your logic.

于 2012-10-21T20:35:32.187 回答
2

@Amulya 100% 正确。但是,如果您想要会话模型而不必调用 getSessionType(),我会考虑使用内置的 parse 方法并从那里创建模型。

如果您的 Session 模型与您的模型相关,我会考虑使用Backbone Relational。由于 Backbone 不处理关系,因此上面列出的插件可以很好地填补空白,而无需过多的体力劳动。

于 2012-10-22T06:40:14.723 回答