javascript事件代理(Event Delegation)

看了几篇文章,放上来供参考

司徒正美的文章Event Delegation Made Easy 

------------------------------------------------------------------自己的理解加深印象-----------------------------------------------------------------------------

What to use when

For really small event handling efforts, the classic solution gives you more control and it is pretty easy to hand over to other developers without much explanation. Event delegation however is probably the only way to keep a large app with a lot of elements to apply handling to (or dynamically loaded elements) in check.

  1. 利用事件机制,父元素的事件(click,mouseover....)去代理它下面所有元素的事件 .

这次项目里面就有这个问题,一个表格,要给每格加1个click事件,假设10行5列(数据很少很少对不对...),传统的写法也要加50个侦听,用eventdelegation 可以节省49

      2.编程中,“不想或不能直接操纵目标对象,用delegate创建一个代理来调用目标对象的方法,从而达到操纵目标对象的目的.毋庸置疑,代理对象拥有目标对象的引用”

司徒的示例代码比较简单(这里有待加深理解...看了下jq这个方法源码...理解还不到位的赶脚...)

var delegate = function(client, clientMethod) {
      return function() {
           return client[clientMethod].apply(client, arguments);
        }
 }
var agentMethod = delegate (client,"clientMethodName");
agentMethod();

或者这种方式

var delegate = function(client, clientMethod) {
      return function() {
           return clientMethod.apply(client, arguments);
        }
 }
var agentMethod = delegate (client,client.method);
agentMethod();

 

完整的就是

            var delegate = function(client, clientMethod) {
                return function() {
                    return client[clientMethod].apply(client, arguments);
                }
            }
            var ClassA = function() {
                var _color = "red";
                return {
                    getColor : function() {
                        console.log("Color: " + _color);
                    },
                    setColor : function(color) {
                        _color = color;
                    }
                };
            };

            var a = new ClassA();
            a.getColor();
            a.setColor("green");
            a.getColor();
            
            var d = delegate(a, "setColor");
            d("blue");
            a.getColor();

 

 

 

 

posted @ 2014-02-26 11:16  NancyChan  阅读(364)  评论(0编辑  收藏  举报