Iron Validate Behavior 中 Validate 函数回调的范围问题
Scope issue with callback in Validate function in Iron Validate Behavior
聚合物 1.*
在父元素中,我使用 Polymer.IronValidatableBehavior
。
回调函数 arg this.setInvalidStates
存在范围问题。在子元素birthdate
中,回调在函数checkIfDateHasValue: function(setInvalidStates) { }
中显示undefined
有没有办法修复作用域,以便我可以将函数 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;
},
当然,您应该使用 bind
,但应用于参数:
.checkIfDateHasValue(this.setInvalidStates.bind(this))
您不需要原始的外部 bind(this)
,因为 checkIfDateHasValue
不是 return 函数,而是布尔值。另外 validate
不应该 return 一个函数,而是一个布尔值,所以 bind
没有意义(在原来的地方)。
聚合物 1.*
在父元素中,我使用 Polymer.IronValidatableBehavior
。
回调函数 arg this.setInvalidStates
存在范围问题。在子元素birthdate
中,回调在函数checkIfDateHasValue: function(setInvalidStates) { }
undefined
有没有办法修复作用域,以便我可以将函数 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;
},
当然,您应该使用 bind
,但应用于参数:
.checkIfDateHasValue(this.setInvalidStates.bind(this))
您不需要原始的外部 bind(this)
,因为 checkIfDateHasValue
不是 return 函数,而是布尔值。另外 validate
不应该 return 一个函数,而是一个布尔值,所以 bind
没有意义(在原来的地方)。