javscript custom object's bubble and capture

不多说,直接上代码。。。 [javascript] (function(){ var hub = { listeners : [], bindObject : function(listener,stopProp){ listener.stopProp = listener.stopProp|| stopProp ||false; listener.stopPropagation = function(){ listener.stopProp = true; }; hub.listeners.push(listener); return hub.bindObject; }, broadcast : function(broadcaster,method,bubble){ for(i=bubble?hub.listeners.length-1:0;bubble?i>-1:i<hub.listeners.length;bubble?i--:i++){ if(broadcaster===hub.listeners[i]){ console.log(broadcaster.name+' is broadcaster'); } if(hub.listeners[i][method]) hub.listeners[i][method](); if(hub.listeners[i].stopProp) break; } } } var computer1 = {name:'computer111'}, computer2 = {name:'computer222'}, computer3 = {name:'computer333'}; computer1.receive = function(){ console.log('computer1 receive the signal!111'); } computer2.receive = function(){ console.log('computer2 receive the signal!222'); } computer3.receive = function(){ console.log('computer3 receive the signal!333'); } hub.bindObject(computer1,true)(computer2)(computer3); hub.broadcast(computer2,'receive'); })(); [/javascript] 简单说明:这个机制是模仿dom事件的冒泡原理来做的,但为了使用方便,我把addEventListener这个函数直接让调控中心hub的bindObject来操作了,这样不用每个对象再手动去通过自己的addEventListener来添加方法,感觉啰嗦,其实dom的冒泡和捕获是基于它的上下级节点关系的,很好处理,在这里我们的自定义对象就明显没有这个上下级关系,没办法,我们只有依它被加载的先后顺序来假定为它的上下级关系,这样很容易就有了冒泡和捕获的机制。其实在日常开发中这个链式关系用的很多,但有一点可以肯定,不是每次运行都会调用所有链式关系,而是对象只关心与它们相关连的对象,至于其它对象他不关心,当然这个机制也可以做到这一点。你可以通过我们的hub把你想要关联的对象捆绑在一起,建立联系。就解决了这个问题。 这就是当前被炒的很火的模块式开发。希望对大家有帮助。不明白或者想讨论的同学,给我留言,或者gtalk我
posted @ 2010-08-16 10:59  7hihi  阅读(268)  评论(0编辑  收藏  举报