所以在使用 RequireJS 之前,我有下面的代码可以正常工作,并从服务器而不是 .fetch() 调用中提取 Posts...考虑到 RequireJS 的模块化模式以及我不能让这个漂亮的 app.posts 变量为其他文件 float 的事实,有没有办法仍然使用 $(document).ready 函数并使 posts 变量仍然响应“重置”事件?目前,我只能让它与 .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)};
集合.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.
},
最佳答案
好吧,我已经回答了我自己的问题。不知道我实际上可以在我的实际 View 中包含一个 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);
},
关于node.js - 在 Backbone 和 RequireJS 中使用listenTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28358811/