在Backbone和RequireJS中使用listenTo
所以在使用RequireJS之前,我有下面的代码工作正常,并从服务器,而不是一个.fetch()调用拉从post…鉴于RequireJS的模块化模式,我不能有这个事实漂亮的app.postsvariables浮动其他文件,是否还有一种方法仍然使用$(document).ready函数,并有postsvariables仍然响应'重置'事件? 目前,我只是得到这个与.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. },
那么我已经回答了我自己的问题。 不知道我实际上可以包括一个要求声明。 这使我可以取消fetch调用,只需传入expressJS index.jade中的所有variables即可
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); },