有一个功能我已经纠结了一段时间了。我使用.where()方法从集合中检索一个对象数组,然后用这个数组重置这个集合。
# 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)它的工作方式与预期一样:事件触发,集合经历重置,View重新呈现重置的集合。但是,当第二次触发事件时,集合不会与服务器同步,并且new_models = collection.where(options)接收到在上一次事件运行中已经重置的集合,并返回一个空数组。
我在这里有什么选择?每次事件运行时,我都需要一个所有模型的初始集合。我应该只在每次运行时请求集合的新实例,还是可以用一种更干净的方式来请求集合的新实例,例如,将原始状态保存在某个地方并将其传递给事件运行,而不是从服务器获取新集合?请给我建议。
发布于 2015-09-29 13:20:52
是。另一种实现方法是,当您过滤集合时,使用.where(),您可以触发Backbone.Events自定义事件,您的视图可以监听这些事件。这样,原始的集合不会重置,只有数组中的更改将触发自定义事件。
在backbone中使用自定义事件的示例代码如下:
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);https://stackoverflow.com/questions/32814299
复制相似问题