使用requireJS在全球范围内提供骨干模型和集合

yok*_*kks 3 requirejs backbone.js backbone-views backbone-routing

我是Web应用程序开发的新手.我有一个名为LoginModel的骨干模型.我想创建它的一个对象,并使其可以从动态加载的任何Backbone View进行全局访问.这是我的模特..

define(['underscore', 'backbone'], function(_, Backbone) {
    LoginModel = Backbone.Model.extend({
        initialize: function(){ },
        defaults:{
            userName: 'undefined',
            userID: 'undefined'
        },
        urlRoot: 'https://xxxx.xx.xxxxxx',
        parse: function(response, options){
            return{
                userName: response.userName,
                userId:response.userId
            };
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

gio*_*_13 5

您可以将新创建​​的对象固定到您正在使用的现有全局对象,例如Backbone:

Backbone.Model.definitions = {
    loginModel : Backbone.Model.extend({...})
}
Run Code Online (Sandbox Code Playgroud)

并使用它作为这个:

new View({model : Backbone.Model.definitions.loignModel});
Run Code Online (Sandbox Code Playgroud)

它可能不是最短的方式,但它比使用不同变量污染全局命名空间更清晰.