2013-04-11 55 views
1

當我的主幹應用程序負載的第一頁,我取一個集合,然後迭代它來渲染頁面:更新骨幹視圖時收集變化

頁路由器:

home: function() 
    { 
     new BodyView ({page:'home'}); 

     new HomeView(); 
     new PostView(); 

     postCollection = new PostCol({userId:getId(),start:0,offset:50}); 
     postCollection.fetch(); 
     postView = new Post({collection:postCollection}); 

    }, 

發表觀點:

el:'.stream', 
    initialize: function() 
    { 
     this.collection.on('reset',this.render.bind(this)); 
     this.collection.on ('change',this.render.bind (this)); 
    }, 
    render: function() 
    { 
     this.collection.each (function (model) 
     { 
      actor = new Actor ({model:model}); 
      this.$el.append (actor.render().el); 
     },this); 
     return this; 
    }, 

我現在想完成的是,當用戶在另一個視圖中保存一些數據時,它會更新Post視圖。這是我做的,但它不工作。

其他景觀:

 post = new PostModel ({userid:getId(),post:postText,objectid:0}); 
      post.save({}, 
      { 
       success: function (response) 
       { 
        postCol = new PostCol ({userId:getId(),start:0,offset:50}); 
        postView = new Post ({collection:postCol}); 
        postCol.fetch().success({change:true}); 
       }, 
       error: function (response) 
       { 
        console.log (response); 
       } 
      } 
      ); 

回答

1

看起來你postCollection是全球性的,所以你可以更新現有的模型,而不是創建一個新的。

// find existing model in the collection. 
var post = postCollection.get(getId()); 
// save model with updated info. 
    post.save({post:postText}, 
    { 
     success: function (response) 
     { 
      // if the save succeeded, the Post view will re-render, 
      // since you are listening for the 'change' event. 
      // so here, you don't really need to do anything. 
     }, 
     error: function (response) 
     { 
      console.log (response); 
     } 

    ); 

代替this.collection.on ('change',this.render.bind (this));在瀏覽後,你可以在個別演員視圖做到這一點,所以整個集合不會重新渲染。

this.model.on ('change',this.render, this); // 'this' as third parameter replaces the `bind` 
+0

該postCollection不是全球性的。我應該讓它成爲全球性的並繼續你的例子嗎? – user2054833 2013-04-11 04:57:04

+0

不一定。您可以創建一個共享集合並將該實例傳遞到兩個視圖中。這個想法是,當一個視圖在共享集合中更改模型時,另一個視圖將接收「更改」事件,然後可以根據需要更新/重新呈現。 – 2013-04-11 05:29:04