[英]Backbone collection.reset( data ) Uncaught TypeError: undefined is not a function
[英]Backbone collection.reset()
因此,我一直在努力使用其中的一部分功能。 我正在使用.where()方法以便從Collection中檢索對象數組,然后使用此數組重置此Collection。
# Fetch the collection
collection = App.request(collection:entites)
console.log collection
>collection {length: 25, models: Array[25] ... }
當事件觸發時,它傳遞.where()方法的選項並開始重置過程:
# Get new models
new_models = collection.where(options)
# Reset collection with the new models
collection.on 'reset', (model, options) ->
console.log options.previousModels
return
collection.reset(new_models)
console.log collection
>collection {length: 5, models: Array[5] ... }
在負責渲染此集合的View中,我監聽'reset'事件並相應地渲染View。
initialize: ->
@listenTo(@collection, 'reset', @render)
它的工作原理與預期的一樣:事件觸發,集合重置,視圖重新渲染重置的集合。 但是當事件第二次觸發時,該集合不與服務器同步,並且new_models = collection.where(options)
接收到一個在先前事件運行中已重置的集合,並返回一個空數組。
我在這里有什么選擇? 每次運行事件時,我都需要使用所有模型的初始集合。 我應該在每次運行時只是請求集合的新實例,還是可以以更簡潔的方式使它實例化,即將原始狀態保存在某個地方,然后將其傳遞給事件運行,而不是從服務器獲取新集合? 請指教。
是。 實現此目標的另一種方法是,當使用.where()過濾集合時,可以觸發Backbone.Events自定義事件,您可以查看該事件。 這樣,原始集合不會重置,只有數組更改會觸發自定義事件。
在骨干網中使用自定義事件的示例代碼是:
var object = {};
_.extend(object, Backbone.Events);
object.on("collectionFiltered", function(arrayOfFilteredModels) {
// do stuff to render your view with the new set of array.
// You can use underscore templating to traverse the array for rendering view.
});
object.trigger("collectionFiltered", collection.where(options);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.