JB´s trash: Recursive DOM walk with Dojo

JB´s trash: Recursive DOM walk with Dojo

čtvrtek, 19. dubna 2012

Recursive DOM walk with Dojo

Ever wanted to recursively walk all children of some DOM node? As far as I was looking for it, DOJO does not support this feature for now. 


With extend function from dojoj/_base/lang I was able to extend Nodelist class, so whenever I use dojo's brilliant query function, I have my custom walk method available.


Just save this as a module wherever you want and include (require) it when you need it.  

define(["dojo/query", "dojo/_base/lang", "dojo/NodeList-traverse",], function(query, lang) {

var NodeList = query.NodeList;

lang.extend(NodeList, {

_walk: function (node, func) {
func(node);
node = query(node).children().first()[0];
while(node) {
this._walk(node, func);
node = query(node).next()[0];
}
},

walk:  function (func) {
this.forEach(function (node) {
this._walk(node, func);
}, this);
}
});

return NodeList;
});
Example of usage:
define([
"dojo/query",
"dojo/NodeList-traverse",
"./NodeList-walk", // !!! your NodeList-walk module
], function(query) {
query('.selector').walk(function(elm) {
console.log(elm)
});
});


Hope you like it! If you find any bug, just let me know in comments.


You can test this on http://jsfiddle.net/joshuaboshi/qpvMn/
原文地址:https://www.cnblogs.com/lexus/p/2821121.html