Ember-自定义计算属性,用于检查是否存在所有依赖字段

Ember - Custom Computed Property to check if all dependent fields exists

本文关键字:存在 依赖 字段 是否 检查 计算 自定义 属性 用于 Ember-      更新时间:2024-02-03

我正在创建一个表单,并试图找到一种简单、优雅的处理方式来查看是否存在所有输入。

Form = Ember.Object.extend({
  // section 1
  name: null,
  age: null,
  isABoolean: null,
  // section 2
  job: null,
  numberOfSiblings: null,
  isComplete: Ember.computed.and('_isSection1Complete', '_isSection2Complete'),
  _isSection1Complete: function() {
    var isPresent = Ember.isPresent;
    return isPresent(this.get('name')) && isPresent(this.get('age')) && isPresent(this.get('isABoolean'));
  }.property('name', 'age', 'isABoolean'),
  _isSection2Complete: function() {
    var isPresent = Ember.isPresent;
    return isPresent(this.get('job')) && isPresent(this.get('numberOfSiblings'));
  }.property('job', 'numberOfSiblings')
});

然而,这似乎并没有扩大规模。我的实际申请会有很多部分(超过20个部分)。

我正在考虑尝试创建一个可重复使用的计算属性,以满足我的需求。以我想要的代码为例:

Form = Ember.Object.extend({
  // properties...
  isComplete: Ember.computed.and('_isSection1Complete', '_isSection2Complete'),
  _isSection1Complete: Ember.computed.allPresent('name', 'age', 'isABoolean'),
  _isSection2Complete: Ember.computed.allPresent('job', 'numberOfSiblings')
});

我觉得这是一种常见的情况,但我无法找到正确的计算属性来执行它,所以我想自己制作。

两个问题:

  1. 定义自定义计算属性的最佳位置在哪里?我可以给Ember.computed附加一个函数吗
  2. 有没有更简单的方法来解决这个问题?我觉得我忽略了一些简单的事情

关于问题#1,

您可以在App命名空间中定义自定义计算辅助对象。在本例中,我创建了一个名为allPresent的新计算帮助程序,该帮助程序根据Ember.isPresent检查传入的每个属性。

App.computed = {
  allPresent: function (propertyNames) {
    // copy the array
    var computedArgs = propertyNames.slice(0);
    computedArgs.push(function () {
      return propertyNames.map(function (propertyName) {
        // get the value for each property name
        return this.get(propertyName);
      }, this).every(Ember.isPresent);
    });
    return Ember.computed.apply(Ember.computed, computedArgs);
  }
};

它可以这样使用,根据您的示例代码:

_isSection2Complete: App.computed.allPresent(['job', 'numberOfSiblings'])

我根据这里的方法进行了调整:http://robots.thoughtbot.com/custom-ember-computed-properties

至于问题2,我想不出更简单的解决方案了。

我不得不对Evan的解决方案进行小的调整,但这对其他需要它的人来说非常有效:

App.computed = {
  allPresent: function () {
    var propertyNames = Array.prototype.slice.call(arguments, 0);
    var computedArgs = propertyNames.slice(0); // copy the array
    computedArgs.push(function () {
      return propertyNames.map(function (propertyName) {
        // get the value for each property name
        return this.get(propertyName);
      }, this).every(Ember.isPresent);
    });
    return Ember.computed.apply(Ember.computed, computedArgs);
  }
};

现在可以这样使用:

_isSection2Complete: App.computed.allPresent('job', 'numberOfSiblings')