2011-11-18 14 views
7

mam tego 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; 
} 

i nazwać tak:

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

Moim problemem jest to, że $(this) w $(this).hide() nie odnosi się do $('.the-element'), ale raczej DOMWindow. Czy jest sposób, w jaki mogę to wykonać?

Odpowiedz

5

Zmian func(); do func.call(this); lub $.proxy(func, this)();.

Można również użyć apply() (nie jest konieczna, gdy call() garnitury) lub bind() (ograniczone wsparcie przeglądarka $.proxy() robi w zasadzie to samo).

0

Jak o:

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

Jestem świadomy, że mogę to zrobić, po prostu nie zachowuje się jak normalna wtyczka jQuery. Lubię używać '$ (this)'. – clem

0

@Alex jest poprawny, wystarczy wymienić func(); na func.call(this); i zadziała. Chciałbym jednak przypomnieć, że robisz 2 redundantne połączenia do konstruktora jQuery w 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; 
    } 

Można sprawdzić to w ten sposób:

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

A potem:

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