2017-03-01 58 views
0

我正嘗試使用一個集合和一個每5秒獲取一次來生成多個視圖。Backbone.js多個視圖,一個集合,一個提取

下面是一個工作示例,但兩個視圖都在刷新時刷新。 我可以將響應拼接到多個網址,但我想最大限度地減少請求的數量。

我目前的問題是,我不希望所有的視圖重新渲染時,每集合5秒,只有相關的視圖改變。 我曾嘗試在集合中創建多個模型,並在解析函數中添加正確的對象,但沒有任何運氣。

響應:

{ 
    "json-1": { 
    "sub_1": "3", 
    "sub_2": [], 
    }, 
    "json-2": { 
    "sub_1": [], 
    "sub_2": "1", 
    }, 
} 

//客戶

const APICollection = Backbone.Collection.extend({ 
    initialize: (models, options) => { 
     this.id = options.id; 
    }, 
    url:() => { 
     return 'https://url.url/' + this.id; 
    }, 
    model: APIModel, 
     parse: (resp) => { 
     return resp; 
    }, 
}); 

const ViewOne = Backbone.View.extend({ 
    initialize: function() { 
     this.collection.bind('sync', this.render, this); 
     this.update(); 
     _.bindAll(this, 'update'); 
    }, 
    render: function (n, collection) { 
     // Render view 
    }, 
    update: function() { 
     let self = this; 
     this.collection.fetch({ 
      update: true, remove: false, success: function() { 
       setTimeout(self.update, 5000); 
      } 
     }); 
    } 
}); 

// Also updates when re-fetched 
const ViewTwo = Backbone.View.extend({ 
    initialize: function() { 
     this.collection.bind('sync', this.render, this); 
    }, 
    render: function (n, collection) { 
     // Render function 
    } 
}); 

let col = APICollection([], {id: 'someid'}); 
new ViewOne({collection: col, el: $("#one")}); 
new ViewTwo({collection: col, el: $("#two")}); 

**更新

澄清: 「只有相關聯的觀點,即改變」。通過這個我的意思是'ViewOne'只應該在'json-1'改變時重新呈現,'ViewTwo'不應該重新呈現。目前完整的回覆將發送到兩個視圖。

+0

「...只有關聯的視圖發生了變化」。 - 您必須澄清這一點,集合中的某些模型是否與某些視圖有關?是什麼使得一個視圖在與集合的工作方式上有所不同? – mikeapr4

+0

我會更新問題 – coop

+0

如果你的回答沒有返回數組,你應該使用'Backbone.Model'而不是'Backbone.Collection',然後你可以在每個視圖中監聽'change:attr'事件。 – mikeapr4

回答

0

當處理返回對象的API而不是對象數組時,最好的方法是直接使用Backbone.Model

update: function() { 
    let self = this; 
    this.model.fetch({ 
     update: true, remove: false, success: function() { 
      setTimeout(self.update, 5000); 
     } 
    }); 
} 

的模式仍然獲取的方式收集相同,但意見可以聽在模型中的特定屬性,而不是:

this.collection.bind('sync', this.render, this); 

可以使用以下

this.model.bind('change:json-1', this.render, this); 

提示:不如listenTo而不是綁定,它是安全的(見docs

this.listenTo(this.model, 'change:json-1', this.render); 
+1

'setTimeout(self.update,5000);'將不起作用,因爲在第一次執行超時回調時上下文將會丟失。相反,您應該使用'fetch'函數的'context'選項並將'this.update.bind(this)'傳遞給'setTimeout'。 –

+1

另外,用這種技術,在第一個錯誤時,5秒循環將停止。 –

+0

@EmileBergeron - 不確定上下文將會丟失,但肯定會有更好的錯誤處理。我會補充一點,如果它是我的代碼,我會在模型內添加重新獲取機制,而不是視圖,就模型/視圖抽象而言,它會更簡潔一些。 – mikeapr4

相關問題