我有一个我认为很容易诊断的问题,但我似乎无法自己解决。
我有以下用 CoffeeScript 编写的缩写 Backbone 代码:
events = FD.Events # collection
# instantiated on page load with collection: events
class FD.StreamView extends Backbone.View
el: $(".stream")
initialize: ->
# Bind the view to listen for a reset of the collection and rerender
@collection.on("reset", @render)
# Listen for a change to this model and run the function getActivities
FD.filters.on("change", @getActivities)
render: =>
# render function code
getActivities: =>
# create a new instance of the FD.Events collection class
events = new FD.Events
# create a new instance of this view, passing in the new empty collection
streamView = new FD.StreamView collection: events, model: FD.filters
# make an AJAX call and as a part of the callback function, reset the collection
# for the view we just instantiated above
params = FD.filters.attributes
callbackFunc = (responseText) ->
json = $.xml2json(responseText)
activities = json.activity
events.reset activities
params = FD.filters.attributes
activities_json = $.get("/landing/Data", params, callbackFunc)
如您所见,问题在于 getActivities 函数在每次调用集合时运行的次数加倍,因为它第一次运行时会创建第二个视图,然后这两个视图都会运行。当集合发生变化时,这两个实例中的每一个都会创建两个实例,所以我们现在有四个,并且所有四个都运行 getActivities。然后是8,然后是16。
显然,创建 FD.StreamView 类的新实例不是正确的方法,但我不知道如何重置单个视图所绑定的集合,以及如何触发绑定的 @render 函数。
任何的想法?如果我遗漏了重要信息,请告诉我。提前致谢。
迈克尔