zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    AFNetworking 3.0 源码解读(四)之 AFURLResponseSerialization
    AFNetworking 3.0 源码解读(三)之 AFURLRequestSerialization
    url 编码(percentcode 百分号编码)(转载)
    AFNetworking 3.0 源码解读(二)之 AFSecurityPolicy
    使用UICollectionView实现首页的滚动效果
    AFNetworking 3.0 源码解读(一)之 AFNetworkReachabilityManager
    c 线程(平行世界)
    ZFPlayer 源码解读
    ios 音视频实现边播边缓存的思路和解决方案 (转)
    c 网络与套接字socket
  • 原文地址:https://www.cnblogs.com/kite-Runner/p/3568673.html
Copyright © 2011-2022 走看看