3

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

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
            };
        }
    });
});
4

3 回答 3

5

您可以将新创建​​的对象固定到您正在使用的已经存在的全局对象上,例如Backbone

Backbone.Model.definitions = {
    loginModel : Backbone.Model.extend({...})
}

并像这样使用它:

new View({model : Backbone.Model.definitions.loignModel});

这可能不是最短的方法,但它比用不同的变量污染全局命名空间更干净。

于 2013-06-05T05:46:25.260 回答
1

与其附加到Backbone.Model原型或全局window范围,我发现将它附加到单独的app对象(由骨干样板和大多数其他实现提供)是有效的。

然后,您app的对象可以被要求进入需要访问当前用户上下文的任何其他模块。

应用程序/app.js

define(function(require, exports, module) {
    "use strict";

    var app = module.exports;

    // Initialize configuration and context objects
    app.root = "/";
    app.currentUser = null; //will be initialized in app/main.js
});

应用程序/main.js

require(["config"], function() {
    require(["app", "LoginModel", "router"], function(app, models, Router) {
        app.currentUser = new LoginModel();
        app.currentUser.fetch();

        app.router = new Router();
    })
});
于 2014-08-06T16:44:09.677 回答
-1

只需创建模型的全局实例,例如

var globalLoginModel = new LoginModel();

或者

window.globalLoginModel = new LoginModel();

然后只需将其传递到您要在其中使用它的任何视图中,例如

new View1({ model : globalLoginModel });
new View2({ model : globalLoginModel });
new View3({ model : globalLoginModel });

应该是这样的。

D

于 2013-06-05T05:42:14.240 回答