Javascript 重置视图集合时如何激发渲染

Javascript 重置视图集合时如何激发渲染,javascript,backbone.js,Javascript,Backbone.js,我才刚开始玩弄脊梁骨。我有一个与集合关联的视图,我希望在集合与服务器成功同步时呈现该视图 我已成功使我的收藏同步- var MyCollection = Backbone.Collection.extend({ model: Backbone.Model, url: '/api/cart/lineitem' }); var myCollection = new MyCollection(); myCollection.fetch({ success:

我才刚开始玩弄脊梁骨。我有一个与集合关联的视图,我希望在集合与服务器成功同步时呈现该视图

我已成功使我的收藏同步-

  var MyCollection = Backbone.Collection.extend({
    model: Backbone.Model,
    url: '/api/cart/lineitem'
  });

  var myCollection = new MyCollection();

  myCollection.fetch({
    success: function() {
      console.log('fetched ' + myCollection.length + ' objects');
    }
  });
控制台显示fetch函数工作正常

然而,在我看来,我有一些奇怪的行为。我似乎无法运行渲染功能

  var MyView = Backbone.View.extend({

    el: $('#mini_cart'),

    cartTpl: _.template($('#miniCartTemplate').html()),

    initialize: function() {
      this.listenTo(this.collection, 'reset', this.render);
      this.listenTo(this.collection, 'reset', console.log('collection reset'));
    },

    render: function(){
      console.log('rendering MyView');
    }

  });

  var myView = new MyView({
    collection: new MyCollection()
  });
控制台显示事件激发,但它从未进入
render
方法(即我收到“集合重置”消息,但从未收到“rendering MyView”消息)。我真的不明白发生了什么(我根本不知道
reset
事件是如何在我的收藏中触发的)

listenTo的第三个参数必须是函数,而不是方法调用(方法调用不返回函数)。请尝试删除此行或将console.log调用包装到如下函数中:

 this.listenTo(this.collection, 'reset', function(){console.log('collection reset');});
创建回调:

myCollection.on('reset', myView.render);

还考虑从视图

使用侦听器
myView.listenTo(myCollection, 'reset', this.render)

我不知道这个方法是否是最干净的方法,但我会在请求完成后提取路由器并重定向:


看起来您正在对集合的一个实例调用
fetch
,然后将另一个(新)实例传递给视图。这意味着不会对视图使用的实例触发“重置”事件

 var myView = new MyView({
    collection: myCollection // use the instance you're going to call fetch on
  });
调用
render
方法时,而不是触发“reset”事件时,将立即执行
console.log
语句。这就是为什么您看到的是log语句,而不是
render
方法中的语句。您可能想做的是:

// Pass a function to the listenTo method which will be executed when the event fires
this.listenTo(this.collection, 'reset', function() {
    console.log('collection reset') 
});

谢谢费迪南德。这就是问题所在——这项活动根本没有被炒掉。看看我为什么回答为什么。谢谢——这绝对是问题所在。
 var myView = new MyView({
    collection: myCollection // use the instance you're going to call fetch on
  });
// Pass a function to the listenTo method which will be executed when the event fires
this.listenTo(this.collection, 'reset', function() {
    console.log('collection reset') 
});