_.result的用例示例

时间:2013-08-30 21:17:46

标签: javascript backbone.js underscore.js

一读到docs for 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');
    }
}

1 个答案:

答案 0 :(得分: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

相关问题