我已经配置了requirejs来加载核心库(jquery,下划线,主干)。 现在我想添加我的主干模型,控制器,视图等以加载asyncronly
我发现了很多关于这个主题的教程和许多“准备好”的样板,我不幸地提到大多数方法都被贬低或相当复杂(即使有更好的方法)。
一个例子是我如何为主库配置requirejs: https://stackoverflow.com/a/10914666/1309847
那么如何使用简单有效的Requirejs配置加载骨干视图,模型,集合,路由器,控制器和模板?
我听了你的建议,但得到了一些奇怪的错误
main.js
require.config({
paths: {
jquery: 'vendors/jquery/jquery',
underscore: 'vendors/underscore/underscore',
backbone: 'vendors/backbone/backbone'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
require(['app'], function(app){
});
app.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Message = new Backbone.Model.extend({
//idAttribute: '_id',
//defaults: { body: '' }
//url: function(){ return this.id ? '/messages/' + this.id : '/messages'; }
});
var newMessage = new Message({ body: 'hi' });
newMessage.save();
});
app.js中出现错误:
Uncaught TypeError: Object [object Object] has no method 'apply'
当我评论新的Backbone.Model.extend部分时,我不会再收到任何错误。
答案 0 :(得分:1)
根据我的经验,引导应用程序的最佳方法是创建Backbone.Router。因此,您可以将URL与应用程序功能相关联。 如果您使用的是RequireJS + Backbone,则可能有一个main.js,其中配置了RequireJS(路径,填充程序等)。第一次打电话给"需要"用于加载初始脚本以引导整个应用程序。 例如:
/**
* main.js - RequireJS bootstrap
*/
require.config({
paths: {
//your paths
},
shim: {
//your shims
}
});
require(
[
'app' //app.js is at the same directory as main.js
],
function(app) {
app.init();
}
);
然后在app.js中你可以创建一个新的路由器实例,或者你可以开始创建视图和模型。
答案 1 :(得分:0)
因此我现在已经明白了:你必须在你自己的自定义js文件周围包装一个requirejs函数。
该函数名为define。第一个参数是您在main.js文件中定义的依赖项数组,或者是您的另一个自定义js的相对路径。 第二个参数是保存原始文件的回调。重要的是,您要返回要共享的对象,函数,数组或变量。
整件事看起来像这样:
define(
['underscore', 'backbone'], // the dependencies (either relative paths or shortcuts defined in main.js
function(_, Backbone){ // the return statement of the deps mapped to a var
var MessageModel = Backbone.Model.extend({ // the original code, file
defaults: { body: '' },
initialize: function(){}
});
return MessageModel; // the return statement, sharing the "final result", sometimes you return the initialize parameter
});
包装模型的集合相同:
define(
['jquery', 'underscore', 'backbone', 'models/message_model'], // deps and the last one is the relative path
function($, _, Backbone,MessageModel){ // same as above explained
var MessageCollection = Backbone.Collection.extend({
model: MessageModel,
initialize: function(){}
});
return MessageCollection;
});
我现在只需弄清楚如何引导整个应用程序。但我认为我需要更多的骨干知识才能做到这一点:)