2011-11-18 11 views
7

मैं इस jQuery प्लगइन है अंदर:

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

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

    return this; 
} 

और यह बहुत की तरह फोन:

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

मेरे समस्या यह है कि $(this)$(this).hide() में का उल्लेख नहीं करता है $('.the-element'), बल्कि DOMWindow। क्या कोई तरीका है कि मैं यह काम कर सकता हूं?

उत्तर

5

func.call(this); या $.proxy(func, this)(); को बदलें func();

तुम भी इस्तेमाल कर सकते हैं apply() (आवश्यक नहीं जब call() सूट) या bind() (सीमित ब्राउज़र समर्थन, $.proxy() अनिवार्य रूप से एक ही बात करता है)।

0

कैसे के बारे में:

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

मुझे पता है कि मैं यह कर सकता हूं, यह सिर्फ एक सामान्य jQuery प्लगइन की तरह व्यवहार नहीं करता है। मुझे '$ (यह)' का उपयोग करने में सक्षम होना पसंद है। – clem

0

@ एलेक्स सही है, आपको func(); को func.call(this); के साथ प्रतिस्थापित करने की आवश्यकता है और यह काम करेगा। तो

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

और::

$.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; 
    } 

आप इस तरह यह सत्यापित कर सकता: हालांकि मैं बाहर बात करने के लिए है कि आप अपने प्लगइन में jQuery निर्माता के लिए 2 अनावश्यक कॉल कर रहे हैं चाहते हैं

console.log($("div").whatIsThis()); 
//"jQuery object" 
संबंधित मुद्दे