【问题标题】:Cannot access to another class inside Requirejs module无法访问 Requirejs 模块中的另一个类
【发布时间】:2014-05-28 19:07:57
【问题描述】:

我无法访问我的“App”对象,尽管我在我的模块中使用定义的语句需要它。你能解释一下为什么我的代码不起作用。

这是我的 main.js 文件:

require(['underscore', 'backbone', 'App'], function(_, Backbone, App) {

    window.App = new App();
    Backbone.history.start();
    return window.App.init();

});

这是我的 app.js 文件:

define(['underscore', 'backbone', 'Views/ApplicationView'], function(_, Backbone, ApplicationView) {
    'use strict';
    var App;
    return App = (function() {

        function App() {

            this.init = __bind(this.init, this);
        }

        App.prototype.init = function() {

            this.view = new ApplicationView();
       };

       return App;

    })();
});

最后是我的 applicationView.js

define(['underscore', 'backbone', 'views/AbstractView', 'App'], function(_, Backbone, AbstractView, App) {
    'use strict';
    var RegisterView;
    return RegisterView = (function(_super) {
        __extends(RegisterView, _super);

        function RegisterView() {
            this.init = __bind(this.init, this);
            return RegisterView.__super__.constructor.apply(this, arguments);
        }



        RegisterView.prototype.init = function() {

            RegisterView.__super__.init.apply(this, arguments);
            this.model = App.user; // APP IS UNDEFINED
        };

    })(AbstractView);
});

【问题讨论】:

    标签: javascript backbone.js coffeescript requirejs


    【解决方案1】:

    我在这段代码中看到的唯一问题是循环依赖。通常,您希望设计代码以避免它们。如果你不能,那么应该修改上面的代码,以便分配this.model(在RegisterView.prototype.init中)的行是这样的:

    this.model = require("App").user;
    

    必须这样,因为模块的工厂函数(给define的匿名函数)将获得的App必然是undefined,因为当RequireJS加载这个模块时,@的模块987654328@ 尚未完成加载。像上面那样执行require 调用会导致RequireJS 稍后在App 的模块完成加载时获取值。

    记录在案的here

    【讨论】:

    • 感谢您的解释,但是当我执行 require("App") 时,它会返回 App 变量的构造函数。然后用户模型未定义
    • 您的评论听起来像是您真正想要的是this.model = window.App.user,它将获得您在window 上设置的App 对象。如果是这样,那么我根本不清楚为什么将 App 放在 applicationView.js 文件的依赖项列表中。
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2016-12-06
    • 2015-12-27
    • 1970-01-01
    • 2017-08-18
    • 2020-12-30
    • 2017-10-26
    • 2015-03-10
    相关资源
    最近更新 更多