在我的应用程序中,我为我的应用程序创建了一个全局空间,说socialApp。甚至在我调用initialize方法之前,我都在窗口中这样声明socialApp

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'scripts/appRoutes',
    'scripts/app/appModel',
    'scripts/app/layout/appLayout'],
    function ($,_,Backbone,Marionette,Routes,appModel,appLayout) {
    "use strict";

    socialApp = window.socialApp || {}; // i am declared the socialApp here.
    socialApp = new Backbone.Marionette.Application();

    socialApp.addInitializer(function(options) {
        socialApp.NewRoute = new Routes;
        socialApp.GenModel = new appModel({router:socialApp.NewRoute}); //i am getting error saying "Uncaught ReferenceError: socialApp is not defined" - why?
        socialApp.Layout = new appLayout();
        socialApp.Layout.render();
        Backbone.history.start();
    });


它并不总是发生,但在某些情况下我遇到此错误。该如何解决呢?

appModel中我这样声明:

define(['jquery','underscore','backbone','marionette'],
    function ($,_,Backbone,Marionette) {
    "use strict";
    socialApp = window.socialApp || {}; //exactly i am getting error from here on refresh some times..
    socialApp.Model = Backbone.Model.extend({
        initialize:function(currentRoute){
            this.router = currentRoute.router;
        }
    });
    return socialApp.Model;
});


我在哪里犯错?有人知道我吗?

最佳答案

您不能像这样在AMD模块中声明全局变量,socialApp是模块本身内的局部变量。因此,可以为您的socialApp变量声明一个AMD模块,如下所示:

File: socialApp.js

define(['marionette'], function(Marionette) {
   var socialApp = {};
   return socialApp;
});


并在您使用它的任何地方都需要socialApp。

File: appModel.js

define(['jquery','underscore','backbone','marionette', 'socialApp'],
    function ($,_,Backbone,Marionette, socialApp) {

    socialApp.Model = Backbone.Model.extend({
        initialize:function(currentRoute){
            this.router = currentRoute.router;
        }
    });
    return socialApp.Model;
});


或者,如果您坚持使用全局变量;在窗口中明确声明socialApp。

socialApp = window.socialApp || {};替换为window.socialApp = window.socialApp || {};

07-28 05:12