我有一个控制器可以观察搜索字段,如下所示:
Scrolls.IndexController = Ember.ArrayController.extend({
searchResult: function() {
var that = this;
this.get('model').set('content', this.store.filter('scroll', function(item) {
var searchTerm = that.get('searchCard');
var regExp = new RegExp(searchTerm, 'i');
return regExp.test(item.get('name'));
}));
}.observes('searchCard')
});
哪个很好用,但是一旦我添加一个覆盖arrangedContent
的方法来限制返回的项目,它就会停止重新渲染。
Scrolls.IndexController = Ember.ArrayController.extend({
arrangedContent: Ember.computed('content', function() {
var count = 0;
return this.get('content').filter(function() {
count++;
return count <= 3;
});
}),
searchResult: function() {
var that = this;
this.get('model').set('content', this.store.filter('scroll', function(item) {
var searchTerm = that.get('searchCard');
var regExp = new RegExp(searchTerm, 'i');
return regExp.test(item.get('name'));
}));
}.observes('searchCard')
});
我怎样才能使我正在做的事情彼此表现良好?
答案 0 :(得分:1)
我在这里看到一些跳出来的东西。第一个是,在控制器的上下文中,content and model are the same thing所以在观察者中,当你这样做时:
this.get('model').set('content'
当我认为您确实打算直接在控制器上设置内容时,您正在模型上设置'content'属性,如下所示:
this.set('content',
我也很想知道你是否真的需要覆盖内容和arrangeContent属性(不确定调用代码是什么样的)。我怀疑这可能会导致一些错误。相反,我想知道你是否可以像这样设置它:
Scrolls.IndexController = Ember.ArrayController.extend({
firstThreeSearchResults: function() {
var count = 0;
return this.get('searchResults').filter(function() {
count++;
return count <= 3;
});
}.property('searchResults'),
searchResults: function() {
var searchTerm = this.get('searchCard');
return this.store.filter('scroll', function(item) {
var regExp = new RegExp(searchTerm, 'i');
return regExp.test(item.get('name'));
});
}.property('searchCard')
});
最终的可能的问题是使用在商店中调用的过滤器函数。根据文档,这个函数:“returns a live RecordArray that remains up to date as new records are loaded into the store or created locally。”问题是,尽管过滤器可能会在添加新结果时更新,但它可能不会导致查找前三个结果的计算属性更新。也就是说,对该计算属性的绑定可能不会触发。解决这个问题的一种方法是做这样的事情:
Scrolls.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find();
}
});
Scrolls.IndexController = Ember.ArrayController.extend({
firstThreeSearchResults: function() {
var count = 0;
return this.get('searchResults').filter(function() {
count++;
return count <= 3;
});
}.property('searchResults'),
searchResults: function() {
var searchTerm = this.get('searchCard');
return this.get('content').filter(function(item) {
var regExp = new RegExp(searchTerm, 'i');
return regExp.test(item.get('name'));
});
}.property('searchCard', 'content.length')
});