Creating nested models with backboneJS + backbone-relational + requireJS

前端 未结 4 769
陌清茗
陌清茗 2020-12-14 12:44

I am new to BackboneJS and I am stuck with nested relations using Backbone-relational Model with RequireJS -I think I runned into circular issues. Any help will be highly ap

4条回答
  •  北海茫月
    2020-12-14 12:58

    I ran into the same problem a while back and followed the approach used by Andrew Ferk for his question: Backbone-relational submodels with RequireJS. The problem arises because you're defining models as Require modules so they don't exist on the global scope, where backbone-relational can look for them. Instead of using global scope (beats the purpose of Require) or exports (bit tricky with the relations), you can define a scope for your models and tell backbone-relational to look for models in it, with addModelScope().

    //modelStore.js - A scope in which backbone-relational will search for models
    //Defined separately so you can access 'modelStore' directly for your models instead of requiring 'app' every time.
    define(['app'], function(app) {
        app.modelStore  = {};
        Backbone.Relational.store.addModelScope(app.modelStore);
        return app.modelStore;
    }
    

    By the way you should shim your Backbone dependency and not need to require jQuery and Underscore for it.

    //ModuleModel (The ModuleModel module. Nice.)
    define(['modelStore', 'backbone', 'backboneRelational'], function(modelStore, Backbone {
        modelStore.ModuleModel = Backbone.RelationalModel.extend({
            relations: [
            {
                type: Backbone.HasMany,
                key: 'groups',
                relatedModel: 'ModuleModel', //Not modelStore.ModuleModel
                collectionType: 'ModuleCollection'
            }
            ]
        });
        return modelStore.ModuleModel;
    });
    

    Kinda late for this now but hope it helps others.

提交回复
热议问题