clem
clem

Reputation: 3534

jQuery $(this) inside a plugin function

I have this jQuery plugin:

$.fn.touchBind = function(func) {
  $(this).live('touchmove', function() {
    $(this).addClass('dragged');
  });

  $(this).live('touchend', function() {
    if ($(this).hasClass('dragged') == false) {
      func();
    }
  });

  return this;
}

and call it like so:

$('.the-element').touchBind(function() {
  $(this).hide();
});

My problem is that $(this) in $(this).hide() doesn't refer to $('.the-element'), but rather DOMWindow. Is there a way I can make this work?

Upvotes: 7

Views: 867

Answers (3)

Esailija
Esailija

Reputation: 140210

@Alex is correct, all you need is to replace func(); with func.call(this); and it will work. However I'd like to point out that you are making 2 redundant calls to jQuery constructor in your plugin:

    $.fn.touchBind = function(func) {

    //this already refers to a jQuery object
      this.live('touchmove', function() {

        //this refers to a DOM element inside here
        $(this).addClass('dragged');
      });

      //this already refers to a jQuery object
      this.live('touchend', function() {

         //this refers to a DOM element inside here
        if ($(this).hasClass('dragged') == false) {
          func.call( this );
        }
      });

      return this;
    }

You could verify it like this:

$.fn.whatIsThis = function(){
return "jquery" in this ? "jQuery object" : "Something else";
};

And then:

console.log( $("div").whatIsThis() );
//"jQuery object"

Upvotes: 0

alex
alex

Reputation: 490143

Change func(); to func.call(this); or $.proxy(func, this)();.

You could also use apply() (not necessary when call() suits) or bind() (limited browser support, $.proxy() does essentially the same thing).

Upvotes: 5

Coding Flow
Coding Flow

Reputation: 21881

How about:

$('.the-element').touchBind(function() {
  $('.the-element').hide();
});

Upvotes: 0

Related Questions