我正在尝试在循环中动态添加观察者。首先,我正在观察display_groups
数组的长度何时发生变化,何时发生变化,我想确保每个显示组都有current_page
属性上的监视(这是用于分页)。 / p>
我在watchDelegate
的循环中添加了一个闭包,它返回关联显示组的当前页面属性。这实际上一切正常,我的问题是我需要访问同一display_group
的另一个属性来执行分页逻辑,我找不到访问正确显示组的方法。我在下面添加了另一个函数displayGroupDelegate
,但它总是返回最后一个循环的显示组。
我对angular(和JS闭包)相当新,所以任何建议都值得赞赏。感谢。
display_group_watchers = []
#watch for when display groups are added/removed
$scope.$watch 'display_groups.length', ((newValue, oldValue) ->
if newValue and (newValue != oldValue)
for watcher in display_group_watchers
watcher() #this clears out existing watchers
display_group_watchers = [] #reset the array
#set up a watch for the current page of each display group
for key, display_group of $scope.display_groups
watchDelegate = ((j) ->
->
$scope.display_groups[j].current_page
)(key)
displayGroupDelegate = ((j) ->
->
$scope.display_groups[j]
)(key)
watcher = $scope.$watch watchDelegate, ((newValue, oldValue) ->
#only fire the change if navigating to a page i.e. going from undefined to 1 is just the inital load of data
if newValue and (newValue != oldValue) and not (newValue ==1 and oldValue == undefined)
########this always returns the last display_group, not the one from the current loop!!!!
console.log "user_tasks_to_expand_sym: #{displayGroupDelegate().user_tasks_to_expand_sym}"
), true
display_group_watchers.push(watcher)
), true