jQuery自定义插件事件

时间:2020-09-07 16:36:38

标签: javascript jquery events

我使用以下代码创建了一个longpress插件:

(function ( $ ) {
 
    $.fn.longpress = function(callback) {
        var timeout = 500;
        this.on('mousedown', function(e){
            $(this).data('start', new Date().getTime());
        });
        this.on('mouseleave', function(e){
            $(this).data('start', 0);
        });
        this.on('mouseup', function(e){
            if(new Date().getTime() >=($(this).data('start') + timeout)){
                callback();
            }
        });
        return this;
    };
 
}( jQuery ));

这是实现

$('#btn').longpress(function()
{
    alert('Long click');
});

我想将其更改为以下内容:

$('#btn').on('longpress', function()
{
    alert('Long click');
});

我想在这里做的是使longpress事件成为全局事件,就像其他事件一样(单击,击键,鼠标键...)。我应该进行哪些更改?

更新:

我已经更新了插件以调用trigger,并使用on来注册事件

(function ( $ ) {
 
    $.fn.longpress = function() {
        var timeout = 500;
        this.on('mousedown', function(e){
            $(this).data('start', new Date().getTime());
        });
        this.on('mouseleave', function(e){
            $(this).data('start', 0);
        });
        this.on('mouseup', function(e){
            if(new Date().getTime() >=($(this).data('start') + timeout)){
                $(this).trigger('longpress');
            }
        });
        return this;
    };
 
}( jQuery ));

这是新的实现方式

$('#btn').longpress().on('longpress', function()
{
    alert('Long click');
});

但仍然不是我想要的。就像我前面提到的本地事件一样,我需要使事件具有全球性。

0 个答案:

没有答案