所以在使用RequireJS之前,我在下面的代码中运行良好并且从服务器中拉入Posts而不是.fetch()调用...给出RequireJS的模块化模式以及我可以&#的事实39; t这个漂亮的app.posts变量浮动其他文件,有没有办法仍然使用$(document).ready函数并让posts变量仍然响应' reset'事件?目前,我只能使用.fetch(见下文)。
routes.js
router.get('/fund', function(req, res) {
Post.find({}, function(err, docs) {
res.render('fund', {
posts: docs //passed to bootstrapPosts in script element
});
});
});
index.jade
var bootstrapPosts = !{JSON.stringify(posts)};
collections.js
app.posts = new app.PostCollection(); //app. == namespacing
app.js
$(document).on('ready', function() {
app.post_appView = new app.postAppView();
app.posts.reset(bootstrapPosts);
app.posts.fetch(); //**Don't want to use this**//
});
post_appView.js
initialize: function() {
this.listenTo(app.posts, 'reset', this.addAll);
}
=====
使用RequireJS
AppView.js
define([
'jquery',
'underscore',
'backbone',
'models/models',
'views/postView',
'collections/collections',
'globals'], function($, _, Backbone, PostModel, PostView, posts, globals){
return AppView = Backbone.View.extend({
el: '#securities',
initialize: function() {
this.listenTo(posts, 'add', this.addOne);
this.listenTo(posts, 'reset', this.addAll);
posts.fetch({reset: true}); // I DON"T WANT TO USE THIS.
},
答案 0 :(得分:1)
我已经回答了我自己的问题。不知道我实际上可以在实际视图中包含一个require语句。这允许我取消fetch调用并传递expressJS中的所有变量index.jade
index.jade
script(type="text/javascript").
require(['lib/domReady', 'collections/collections', 'globals'], function (domReady, posts, globals) {
domReady(function() {
posts.reset(globals.bootstrapPosts);
});
});
appView.js
define([
'jquery',
'underscore',
'backbone',
'models/models',
'views/postView',
'collections/collections',
'globals'], function($, _, Backbone, PostModel, PostView, posts, globals){
return AppView = Backbone.View.extend({
el: '#securities',
initialize: function() {
this.listenTo(posts, 'add', this.addOne);
this.listenTo(posts, 'reset', this.addAll);
},