我试图使用一个HTML标记在我的Ember.ArrayController子类中设置动态排序,如下所示:
App.ListController = Ember.ArrayController.extend
sortOptions: [{id: 0, text: 'Price High-Low', sortBy: 'pricing', sortAsc: false},
{id: 1, text: 'Price Low-High', sortBy: 'pricing', sortAsc: true},
{id: 2, text: 'Name Ascending', sortBy: 'name', sortAsc: true},
{id: 3, text: 'Name Descending', sortBy: 'name', sortAsc: false}]
currentSortOptionId: 0
sortBy: (->
this.get('sortOptions')[this.get('currentSortOptionId')].sortBy
).property('currentSortOptionId')
# Override
sortProperties: (->
[this.get('sortBy')]
).property('sortBy')
# Override
sortAscending: (->
this.get('sortOptions')[this.get('currentSortOptionId')].sortAsc
).property('currentSortOptionId')
在我的模板里,我有:
Sort by {{view Ember.Select content=sortOptions
optionValuePath="content.id"
optionLabelPath="content.text"
value=currentSortOptionId}}
{{#each listing in controller.arrangeContent}}
...
{{/each}}
更改选择器大部分时间起作用,并且总是在切换sort属性时起作用。然而,排序方向(通过"sortAscending")属性变得混乱,有时似乎在后面有一个操作(即。为“sortAscending”使用先前选定的值)。
这里会发生什么事?
编辑:下面是一个孤立示例的JSFiddle:http://jsfiddle.net/s9AFr/3/
如果您更改排序选择器几次,您可以说服自己,它在某些时候排序不正确,特别是在排序的升序/降序功能方面。这种方式似乎“滞后”于用户的选择。
发布于 2014-01-29 07:47:37
不幸的是,我认为这是由于一个错误。
为什么会这样
基本上现在发生的事情是,Ember并不期望sortProperties和sortAscending同时发生变化。在SortableMixin的sortAscendingWillChange
观察者中,我们跟踪sortAscending
的旧值(将其存储在_lastSortAscending
中),然后,在after观察者中,如果sortAscending
确实这样做了,那么它们只是数组
sortAscendingDidChange: Ember.observer('sortAscending', function() {
if (get(this, 'sortAscending') !== this._lastSortAscending) {
var arrangedContent = get(this, 'arrangedContent');
arrangedContent.reverseObjects();
}
}),
当您同时设置sortAscending
和sortProperties
时,如观察者之前的sortAscendingWillChange
触发,保留旧的sortAscending属性,则由于sortProperties
更改,数组将重新排序,使用sortAscending
的新值(因此,此时,一切都按您的预期排序).但是最后,sortAscendingDidChange
观察者触发,看到sortAscending是不同的,所以它再次翻转整个数组。
编辑:工作(JSfiddle)
考虑到这个错误的原因,我认为解决方法是确保sortAscending
和sortProperties
不会同时发生变化。
因此,与其将sortAscending
设置为计算属性,我们还可以在观察currentSortOptionId
的观察者中设置它,注意在下一个运行循环中设置它(因此我们使用Ember.run.later
)。这样,sortProperties
计算的属性将首先更改,内容将被排序,然后设置sortAscending
属性。
https://stackoverflow.com/questions/21412453
复制相似问题