requireJS中的Backbone.js + underscore.js + jQuery ......这是正确的方法吗?

时间:2012-08-12 14:03:03

标签: jquery backbone.js requirejs underscore.js

我正在尝试更多地了解requireJS。所以,如果我理解正确,那么下面的代码应该是合法的。这是使我的应用程序模块化的正确方法吗?

这是application.js,其中data-main属性指向:

requirejs.config({
    baseUrl: 'scripts/vendor', // By default, load all from vendor folder
    shim: {
        'backbone' : { // Do not support module loading
            deps: ['underscore', 'jquery'], // Do not support module loading
            exports: 'Backbone' 
        },
    },
    paths: {
        models: '../application/models', // Load from this folder if starts with user
        views: '../application/views',   // As above...
    }
});

requirejs(['jquery', 'backbone', 'views/user'], function($, Backbone, UserView) {
});

我的视图/模型模块(现在很无用):

档案application/views/user.js

// underscore should be loaded now
define(['jquery', 'backbone', 'models/user'], function($, Backbone, User) { 
    return Backbone.View.extend({
        model: User,

        el: $('tr'),    

        initialize: function() {}
    });
});

档案application/models/user.js

define(['backbone'], function(Backbone) { // underscore should be loaded now
    return Backbone.Model.extend({
    });
});

2 个答案:

答案 0 :(得分:5)

你也需要使用下划线,因为它不兼容AMD。

 underscore: {
  exports: '_'
}

我建议调查https://github.com/tbranyen/backbone-boilerplate/因为使用RequireJS需要很多麻烦。

答案 1 :(得分:1)

使用lodash代替下划线,是一种卓越的完全兼容解决方案并支持AMD负载。检查基准和文档;)

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: { 
        'jquery': ['//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min','libs/jquery-min'],
        'lodash': 'libs/lodash.min',
        'backbone': 'libs/backbone.min',
    },
    shim: {
        'backbone': {deps:['lodash','jquery'], exports: 'Backbone'}
    }
});

require([
    'jquery', 'lodash','backbone'
],
function($, _){
    return {};
});