RequireJS 2.0 - 定义我的Backbone.Router

时间:2012-07-27 12:46:03

标签: javascript backbone.js undefined requirejs

我目前正在尝试使用RequireJS 2.0,因此必须更改一些代码。 这是我的main.js,在data-main中使用index.phtml启动。

编辑:忘记项目结构,可能很有用:)

->public

 -> css
 -> js
 app.js
 facade.js
 main.js
 router.js
 ...
  -> collections
  -> libs

   -> backbone
   -> jquery
   -> json2
   -> plugins
   -> require
   -> underscore

 -> templates
...


// Filename: main.js

// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.

require.config({
    //Here baseUrl = /js (Loaded in data-main in logged.phtml)
    // 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.7.2.min")
    paths: {
        jQuery: 'libs/jquery/jquery',
        Underscore: 'libs/underscore/underscore',
        Backbone: 'libs/backbone/backbone',
        JSON: 'libs/json2/json2',
        templates: '../templates'
    },

    // Sets the configuration for your third party scripts that are not AMD compatible
    shim: {
        'libs/plugins/bootstrap-min': ['jQuery'],
        'libs/plugins/jquery.cookies.min': ['jQuery'],
        'jQuery': {
            exports: '$'
        },
        'JSON': {
            exports: 'JSON'
        },
        'Underscore': {
            exports: '_'
        },
        'Backbone': {
            deps: ['Underscore', 'jQuery'],
            exports: 'Backbone'  // attaches "Backbone" to the window object
        }
    }
});

define([
    // Load our app module and pass it to our definition function
    'app',
    'jQuery',
    'Underscore',
    'Backbone',
    'JSON'
], function(App) {
    // The "app" dependency is passed in as "App"
    // Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
    App.initialize();
});

我尝试将'router'添加到此文件及其依赖项,但没有任何更改,所以我认为它没用。

这是在调用App时加载的app.js:

define([
    'jQuery',
    'Underscore',
    'Backbone',
    'JSON',
    'router', // Request router.js
    'i18n!nls/langs',
    'facade',
    //'order!libs/plugins/jquery.backstretch.min'
    //'libs/plugins/backbone.validation.min'
], function($, _, Backbone, JSON, Router, langs, facade) {
var initialize = ...
...
...
return {
        initialize: initialize
    };
});

问题出在我的router.js定义中,我使用了console.log,它告诉我它正在返回正确的对象。

但是当我在router中致电app.js时,router仍未定义。 我可能犯了一个错误,但我找不到它。

编辑:添加了router.js代码

require([
    'jQuery',
    'Underscore',
    'Backbone',
    'JSON',
    'facade',
    'models/UserModel',
    'libs/plugins/jquery.cookies.min'
], function($, _, Backbone, JSON, facade, User, cookies){
    var AppRouter = Backbone.Router.extend({
...
    });

    var app_router = new AppRouter;
        // Start Backbone history a neccesary step for bookmarkable URL's
        Backbone.history.start();
    return app_router;
});

1 个答案:

答案 0 :(得分:3)

您的router.js文件未正确定义AMD模块。您需要使用define,而不是require