Node.js 在主干和RequireJS中使用listenTo
因此,在使用RequireJS之前,我有下面的代码,这些代码运行良好,从服务器而不是.fetch()调用中提取帖子……考虑到RequireJS的模块化模式以及我不能让这个漂亮的app.Posts变量在其他文件中浮动的事实,有没有办法仍然使用$(文档).ready函数,且posts变量仍对“重置”事件作出响应?目前,我只将其用于.fetch(见下文) routes.jsNode.js 在主干和RequireJS中使用listenTo,node.js,backbone.js,requirejs,Node.js,Backbone.js,Requirejs,因此,在使用RequireJS之前,我有下面的代码,这些代码运行良好,从服务器而不是.fetch()调用中提取帖子……考虑到RequireJS的模块化模式以及我不能让这个漂亮的app.Posts变量在其他文件中浮动的事实,有没有办法仍然使用$(文档).ready函数,且posts变量仍对“重置”事件作出响应?目前,我只将其用于.fetch(见下文) routes.js router.get('/fund', function(req, res) { Post.find({}, functio
router.get('/fund', function(req, res) {
Post.find({}, function(err, docs) {
res.render('fund', {
posts: docs //passed to bootstrapPosts in script element
});
});
});
翡翠索引
var bootstrapPosts = !{JSON.stringify(posts)};
script(type="text/javascript").
require(['lib/domReady', 'collections/collections', 'globals'], function (domReady, posts, globals) {
domReady(function() {
posts.reset(globals.bootstrapPosts);
});
});
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);
}
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);
},
=====
带着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.
},
我已经回答了我自己的问题。我不知道我可以在我的实际视图中包含require语句。这使我可以省去fetch调用,只需传入expressJS index.jade中的所有变量 翡翠索引
var bootstrapPosts = !{JSON.stringify(posts)};
script(type="text/javascript").
require(['lib/domReady', 'collections/collections', 'globals'], function (domReady, posts, globals) {
domReady(function() {
posts.reset(globals.bootstrapPosts);
});
});
appView.js
initialize: function() {
this.listenTo(app.posts, 'reset', this.addAll);
}
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);
},