Iron Validate Behavior中Validate函数中回调的范围问题

时间:2018-02-26 17:30:56

标签: javascript polymer polymer-1.0

聚合物1。*

在父元素中,我使用Polymer.IronValidatableBehavior

我对回调函数arg this.setInvalidStates存在范围问题。在子元素birthdate中,回调在函数undefined中显示checkIfDateHasValue: function(setInvalidStates) { }

有没有办法修复范围,以便我可以传递函数this.setInvalidStates作为回调?

父元素:

  setInvalidStates: function() {
    ...
  },

  validate: function() {
    if (this.required) {
      return this.$.birthdate
        .checkIfDateHasValue(this.setInvalidStates).bind(this);
    }

    return true;
  },

生日子元素:

checkIfDateHasValue: function(setInvalidStates) {
  if (!this.$.datePicker.value) {
    setInvalidStates(true);

    this.errorMessage = '*birth date required under certain '
      + 'choices';

    return false;
  }

  return true;
},

1 个答案:

答案 0 :(得分:2)

Sure, you should use bind, but applied to the argument:

.checkIfDateHasValue(this.setInvalidStates.bind(this))

You don't need the original, outer bind(this), as checkIfDateHasValue does not return a function, but a boolean. Also validate should not return a function, but a boolean, so bind does not make sense then (at the original place).