0

当我阅读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');
    }
}
4

1 回答 1

6

_.result有一个非常简单的目的(与下划线中的大多数函数一样)。它使您可以从对象中获取命名值,而无需知道或关心该值是存储为属性还是方法。因此:

var nameProperty = {name: 'Peter'};
var nameMethod = {name: function () {return 'Peter';}};
console.log(_.result(nameProperty, 'name'));
console.log(_.result(nameMethod, 'name'))

在这两种情况下,代码都可以正常工作,成功记录名称并且不会抛出TypeError.

这就是它的全部目的。这非常简单明了。

现实世界的例子是Backbone.Model.url.

于 2013-08-30T22:11:05.520 回答