嵌套Backbone.js的集合更好的解决方案 [英] Better solution for nested Backbone.js collections

查看:182
本文介绍了嵌套Backbone.js的集合更好的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的许多骨干机型经常处理嵌套模型和收藏,至今​​我使用默认选项的组合解析的toJSON 手动实现排料:

Many of my Backbone models often deal with nested models and collections, so far I'm using a combination of defaults, parse and toJSON manually to achieve nesting:

ACME.Supplier = Backbone.Model.extend({
    defaults: function() {
        return {
            contacts: new ACME.Contacts(),
            tags: new ACME.Tags(),
            attachments: new ACME.Attachments()
        };
    },

    parse: function(res) {
        if (res.contacts) res.contacts = new ACME.Contacts(res.contacts);
        if (res.tags) res.tags = new ACME.Tags(res.tags);
        if (res.attachments) res.attachments = new ACME.Attachments(res.attachments);

        return res;
    }
});

ACME.Tag = Backbone.Model.extend({
    toJSON: function() {
        return _.pick(this.attributes, 'id', 'name', 'type');
    }
});

我在几个插件看在那里,基本上没有与以上相同,但少了很多控制和更多的样板,所以我想知道如果任何人有一个更优雅的解决方案,这种常见的Backbone.js的问题。

I've looked at a few plugins out there that basically does the same as above but with a lot less control and more boilerplate, so I'm wondering if anyone has a more elegant solution to this common Backbone.js problem.

编辑:我结束了以下办法:

ACME.Supplier = Backbone.Model.extend({
    initialize: function(options) {
        this.tags = new ACME.Tags(options.tags);
    },

    parse: function(res) {
        res.tags && this.tags.reset(res.tags);

        return res;
    }
});

ACME.Tag = Backbone.Model.extend({
    toJSON: function() {
        return _.pick(this.attributes, 'id', 'name', 'type');
    }
});

值得注意的是,后来我发现,你需要从构造函数传递嵌套模型/收集到的数据通过选项嵌套模式对象的构造函数

推荐答案

我不明白你的方法有问题。

I don't see any problem with your approach.

恕我直言 Model.parse()的方法如果此:是在特殊情况下的行为解析需要重写

IMHO the Model.parse() method if for this: to be overwritten in case special parse behavior needs.

唯一想我会改变会是这样的事情:

The only think I'd change would be things like this:

if (res.tags) res.tags = new ACME.Tags(res.tags);

有关这一点:

if (res.tags) this.tags.reset(res.tags);

由于你已经有了 ACME.Tags 集合的一个实例我会再次使用它。

Due you already have an instance of ACME.Tags collection I'd reuse it.

另外,我真的不喜欢的实施,我用来做在 Model.initialize)这个初始化(<在默认/ code>,但我认为这是一个品味的问题。

Also I don't really like the defaults implementation, I'm used to do this initializations in the Model.initialize() but I think is a matter of taste.

这篇关于嵌套Backbone.js的集合更好的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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