在jQuery对象中转换lodash / underscore集合(链接)

时间:2014-05-29 17:22:34

标签: javascript jquery lodash

我想将lodash集合无缝地包装在jQuery对象中。现在我将lodash输出保存在变量中并将其提供给jQuery:

//simplified code
var els = [document.getElementById('a'), document.getElementById('b')];
els = _(els)
    .map(doStuff)
    .map(doMoreStuff);
var $els = $(els);

但我想把它链接起来:

//pseudo code
_(els)
    .map(doStuff)
    .map(doMoreStuff)
    .jQueryfy() //this magic method, missing
    .show() //jQuery method, right away

我认为可以使用tap,但实际上并没有更改集合。

_(els)
    .map(doStuff)
    .map(doMoreStuff)
    .tap(function(array) { return $(array); }) //doesn't actually return a jQuery object
    .show()

1 个答案:

答案 0 :(得分:1)

这应该通过mixinjQuery constructor一起使用,它确实采用了一系列DOM元素:

_.mixin({jQueryfy: jQuery}, {chain:false});

请注意,jQuery本身已经支持基本collection manipulation functions,因此您可以编写示例以及

$("#a, #b").map(doStuff).map(doMoreStuff).show();