2015-02-06 61 views
2

我有幾個操作cheerio對象的功能。對於幾乎所有這些功能,我必須將元素與自身一起傳遞給$。

例子:

function aUtilityFunc($, cheerioEl) { // <- $ in the params 
    return cheerioEl.each(function (i, child) { 
     // i do not want to do this: 
     $(child).attr("something", $(child).attr("something") + "something"); 

     // i would rather do this and omit the $ in the params (like with global jquery doc): 
     var $ = cheerioEl.$; 
     $(child).attr("something", $(child).attr("something") + "something"); 
    }); 
} 

有一種優雅的解決這個問題,讓我通過只有1參數去我的功能呢? (我不是說將它們包裝到一個對象文字中:>)。因爲坦率地說,這種方式並不好(除非我忽略了某些東西)。

+3

爲什麼你需要通過''$呢?你不能只在你的模塊的頂部有'var $ = require('cheerio');'? – Jack 2015-02-06 02:54:43

回答

3

好像你可以只是做這樣的事情:

var $ = require('cheerio'); 

function aUtilityMethod(cEls) { 
    cEls.each(function(i, a) { 
     console.log("li contains:", $(a).html()); 
    }); 
} 


// testing utility method 
(function() { 
    var fakeDocument = "<html><body><ol><li>one</li><li>two</li></ol></body></html>", 
     myDoc = $(fakeDocument), 
     myOl = $("ol", myDoc.html()); 

    aUtilityMethod(myOl.find("li")); 
})();