浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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/
posted on 2012-12-17 00:25  lexus  阅读(216)  评论(0编辑  收藏  举报