【问题标题】:Emberjs filter() versus filterProperty()Emberjs filter() 与 filterProperty()
【发布时间】:2013-05-31 06:28:34
【问题描述】:

看起来filter() 和filterProperty() 很相似,都是返回过滤数组的可枚举函数。

在什么情况下我应该使用其中一种?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    更新: filterProperty() 已被 filterBy() 取代。用法相同,见下方评论。

    filterBy() 是filter() 的快捷方式,可让您根据可枚举元素的指定属性快速过滤可枚举。如果您需要做一些更复杂或不寻常的事情,而您不能使用filterBy(),请使用filter()。

    例如,假设你有一个这样的对象数组:

    [
      {firstName: 'Kris', lastName: 'Selden'},
      {firstName: 'Luke', lastName: 'Melia'},
      {firstName: 'Formerly Alex', lastName: 'Matchneer'}
    ]
    

    并且您希望有一个计算属性,该属性使用过滤数组以仅包含具有firstName == 'Luke' 的人:

    使用filter():

    filterComputed: function() {
      return this.get('content').filter(function(item, index, enumerable){
        return item.firstName == 'Luke';
      });
    }.property('content.@each')
    

    使用filterBy():

    filterByComputed: function() {
      return this.get('content').filterBy('firstName', 'Luke');
    }.property('content.@each')
    

    JSBin example

    【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2023-03-27
    • 2016-10-26
    • 1970-01-01
    • 2011-10-17
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多