2011-11-18 6 views
7

tengo este plugin de jQuery:

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

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

    return this; 
} 

y lo llaman así:

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

Mi problema es que $(this) en $(this).hide() no se refiere a $('.the-element'), sino más bien DOMWindow. ¿Hay alguna manera de que pueda hacer que esto funcione?

Respuesta

5

Cambio func();-func.call(this); o $.proxy(func, this)();.

También es posible usar apply() (no es necesario cuando call() trajes) o bind() (soporte de los navegadores limitado, $.proxy() hace esencialmente la misma cosa).

0

¿Qué tal:

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

Soy consciente de que puedo hacer esto, simplemente no se comporta como un plugin jQuery normal. Me gusta poder usar '$ (this)'. – clem

0

@Alex es correcto, todo lo que necesita es reemplazar func(); con func.call(this); y funcionará. Sin embargo, me gustaría señalar que usted está haciendo 2 llamadas redundantes a jQuery constructor en la 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; 
    } 

Se puede verificar de esta manera:

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

Y luego:

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