RequireJS + BackboneRelational +自引用 [英] RequireJS + BackboneRelational + Self-Referential

查看:197
本文介绍了RequireJS + BackboneRelational +自引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在这里跟随例如:与backboneJS创建嵌套模型+骨干关系+ requireJS

I've been trying to follow the example here: Creating nested models with backboneJS + backbone-relational + requireJS

和结束有一些不同的东西(因为我需要一个Backbone.Collection,而不是一个Backbone.RelationalModel):

And ended up having something different (since I need a Backbone.Collection, not a Backbone.RelationalModel):

define(['exports', 'backbone', 'backbone.relational'], function (Exports, Backbone) {
    var ModuleModel = Backbone.RelationalModel.extend({
        relations : [{
                        type : Backbone.HasMany,
                        key : "children",
                        relatedModel : 'ModuleModel',
                        collectionType : 'ModuleCollection'
                     }] 
    });
    Exports.ModuleModel = ModuleModel;
    return ModuleModel;
});

define(['exports', 'backbone'], function(Exports, Backbone) {
    var ModuleCollection = Backbone.Collection.extend({
        model : Exports.ModuleModel,
    });
    Exports.ModuleCollection = ModuleCollection;
    return ModuleCollection;
});

但是,当我做的:

But, when I do:

var modules = new ModuleCollection();
modules.fetch();

我得到:

TypeError: this.model is undefined

和它是一种显而易见的,因为Exports.ModuleModel创建的之后的ModuleCollection已被初始化。

And it's kind of obvious since Exports.ModuleModel is created after ModuleCollection has been initialized.

这是如何实现这种自我指涉的模型任何提示?

Any hints on how to achieve this self-referential model?

在此先感谢!

推荐答案

好吧,我解决了它在全球范围内暴露的命名空间(只是删除 VAR

Ok, I solved it by exposing the namespaces in the global scope (just removed var).

我不知道这是AMD的投诉,但至少它看起来并不那么糟糕:

I don't know if this is AMD complaint, but at least it doesn't look that bad:

define(['backbone', 'backbone.relational'], function (Backbone) {
    ModuleModel = Backbone.RelationalModel.extend({
        relations : [{
                        type : Backbone.HasMany,
                        key : "children",
                        relatedModel : 'ModuleModel',
                        collectionType : 'ModuleCollection'
                     }] 
    });
    return ModuleModel;
});

define(['backbone', 'models/module'], function(Backbone, ModuleModel) {
    ModuleCollection = Backbone.Collection.extend({
        model : ModuleModel,
    });
    return ModuleCollection;
});

如果有人有更好的解决方案,随意张贴了!

If someone has a better solution, feel free to post it!

这篇关于RequireJS + BackboneRelational +自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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