BenM
BenM

Reputation: 53198

jQuery Event Plugin issues

Following on from my earlier question, I have decided to have a go at writing a series of jQuery plugins that mimic mobile events (tap, taphold, etc.).

I have the concept working, but am having problems executing the handler functions. Here's how I am defining the plugin methods:

(function($) {
    var touch_capable = isTouchCapable();

    var settings = {
        swipe_h_threshold : 30,
        swipe_v_threshold : 50,
        taphold_threshold : 750,
        startevent        : (touch_capable) ? 'touchstart' : 'mousedown',
        endevent          : (touch_capable) ? 'touchend'   : 'mouseup'
    };

    // tap Event:
    $.fn.tap = function(handler) {
        return this.each(function() {

            var $this = $(this);
            var started = false;            

            $this.bind(settings.startevent, function() {
                started = true;
            });

            $this.bind(settings.endevent, function() {              
                if(started)
                {
                    handler();
                }
            });
        });
    };
}) (jQuery);

And then I can bind these 'events' using $('#a_div').tap();. The problem that I have is this one:

If I pass in a function to the tap() method which works upon the element, there's an error. For example:

$('#my_div').tap(function() { alert($(this).get()) });

Actually alerts [object DOMWindow]. Can anyone point me in the direction of correctly executing the handler function? Could it be somehow related to event propagation?

Upvotes: 0

Views: 106

Answers (1)

Matt
Matt

Reputation: 75317

You can use the Function.prototype.call and Function.prototype.apply methods to set the execution context of a function;

$this.bind(settings.endevent, function() {              
    if(started)
    {
        handler.call(this);
    }
});

This allows you to minic the interface bind provides to the provided handler;

$this.bind(settings.endevent, function() {              
    if(started)
    {
        handler.apply(this, arguments);
    }
});

Now the handler will receive the event object as it's first parameter, and this will be set the the element the event fired on.

Upvotes: 1

Related Questions