当我阅读underscore.js' _.result 的文档时,我认为它在表单验证的上下文中可能很有用。所以在我的主干视图中,我有一个保存方法如下:
save : function() {
var values = _.reduce(this.$el.find(":input"), function(values, input) {
values[input.name] = input.value;
return values;
}, {});
this.showErrors(_.result(this.validate(values), 'unlessValid'));
/*
NOTE: I've concluded this is a more idiomatic underscore.js approach
_.compose(submitForm, _.wrap(unlessFormInvalid, showFormErrors));
However I've left out 'this.' to reduce the 'noise', and yet the calls
to '_.compose' and '_.wrap' make this noisier than I'd like anyway, and
would undoubtedly be exacerbated in cases where there are more than just
'unless' and (implicit above) 'if' conditions. Therefore I'm becoming more
inclined to implement my own sort of promise/'thennable' interface, such as:
this.validateForm().then({
onValid: this.submitForm,
onInvalid: this.showFormErrors
});
*/
}
我觉得最后一行很好地描述了这个过程。但是我的实现似乎有点矫枉过正,因为我总是只返回一个具有一个属性的对象:'unlessValid'。以下是其他方法的完整“管道”,它们按预期工作。但是,对于 underscore.js 的 _.result 功能的其他可能更好的用例示例,我会很好奇。
submissionErrors : function(values) {
console.log('inside submissionErrors -- always get here');
console.log('but only reach showErrors if submissionErrors returns value');
// return {};
},
validate : function(values) {
var unlessValid = this.submissionErrors(values) || this.persist.call(this, values);
return {
unlessValid: unlessValid
}
},
persist : function(values) {
console.log('inside persist');
},
showErrors : function(errors) {
if (errors) {
console.log('inside show Errors');
}
}