JQuery $ (this) inside the 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 name it like this:

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

My problem is that $(this) in $(this).hide() does not apply to $('.the-element') , but rather DOMWindow . Can I do this job?

+7
source share
3 answers

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

You can also use apply() (not necessary when call() is suitable) or bind() (limited browser support, $.proxy() does almost the same thing).

+5
source

What about:

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

@Alex is correct, all you need to do is replace func(); at func.call(this); and it will work. However, I would like to point out that you make 2 redundant calls to the 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 can check it as follows:

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

And then:

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

All Articles