node.js - 在 Backbone 和 RequireJS 中使用listenTo

标签 node.js backbone.js requirejs

所以在使用 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/

相关文章:

javascript - Require.js 甚至在 IF 语句中加载模块

ember.js - EmberJs路由

node.js - Mongoose验证错误: Invalid schema configuration

javascript - backbone.js 更改模型的 url 参数并且获取不更新获取的数据

backbone.js - RequireJs - Backbone.Views 相互依赖

backbone.js - HandleBars 使用 RequireJS 和 BackboneJS 进行编译

javascript - 主干 -> 无法调用未定义的方法 'remove'

Javascript/Sails.js Controller 等待服务调用异步函数

javascript - 拆分express和app有什么目的吗?

node.js - React.js 从本地文件读取