【代码片-1】 jQuery事件扩展机制

浏览: 98 发布日期: 2016-12-01 分类: jquery
///////
(function(){
    if(!jQuery || !$){
        return;
    }

    var maybeTrigger = function($e){
        if(!$e.data("ime")){
            var value = ($e[0].contentEditable === "true"? $e.html(): $e.val());
            if(value !== $e.data("lastValue")){
                $e.trigger("textchange", [$e.data("lastValue")]);
                $e.data("lastValue", value);
            }
        }
    }

    var imeStart = function(){
        $(this).data("ime", true);
    }

    var imeEnd = function(){
        $(this).data("ime", false);
    }

    var handler = function(){
        maybeTrigger($(this));
    }

    var delayHandle = function(){
        var $e = $(this);
        setTimeout(function(){maybeTrigger($e)}, 25);
    }

    jQuery.event.special.textchange={
        setup:function(data,namespace, eventHandle){
            var $target = $(this);
            $target.data("ime",false);
            $target.data("lastValue",this.contentEditable==="true"? $target.html(): $target.val());
            $target.bind("compositionstart.textchange", imeStart);
            $target.bind("compositionend.textchange", imeEnd);
            $target.bind("keyup.textchange", handler);
            $target.bind("cut.textchange paste.textchange input.textchange", delayHandle);
        },

        teardown:function(namespaces){
            $(this).unbind(".textchange");
        }
    }
})();
返回顶部