只要我閱讀docs for underscore.js' _.result,我認爲它在表單驗證的上下文中可能很有用。所以在我的骨幹視圖我有一個保存方法如下:_.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');
}
}
骨幹本身使用'.result'。 –
無論誰投票結束這個(並且下調了它),因爲這被認爲主要是基於意見的,你會錯的。我要求提供其他用例的例子,「可能更好」,但任何例子。 –
我不認爲你的代碼受益於'_.result';它會表現相同,如果你只是'this.showErrors(this.validate(values));'和'validate'只是返回'this.submissionErrors(values)|| this.persist.call(this,values);'。你似乎永遠不會在'unlessValid'中返回一個函數... – bfavaretto