[英]jQuery Event Plugin issues
在我之前的問題之后,我決定嘗試編寫一系列jQuery插件來模擬移動事件(點擊,taphold等)。
我有這個概念,但是執行處理程序功能時遇到問題。 這是我定義插件方法的方式:
(function($) {
var touch_capable = isTouchCapable();
var settings = {
swipe_h_threshold : 30,
swipe_v_threshold : 50,
taphold_threshold : 750,
startevent : (touch_capable) ? 'touchstart' : 'mousedown',
endevent : (touch_capable) ? 'touchend' : 'mouseup'
};
// tap Event:
$.fn.tap = function(handler) {
return this.each(function() {
var $this = $(this);
var started = false;
$this.bind(settings.startevent, function() {
started = true;
});
$this.bind(settings.endevent, function() {
if(started)
{
handler();
}
});
});
};
}) (jQuery);
然后,我可以使用$('#a_div').tap();
綁定這些“事件” $('#a_div').tap();
。 我的問題是這個:
如果我將一個函數傳遞給對元素起作用的tap()
方法,則會出現錯誤。 例如:
$('#my_div').tap(function() { alert($(this).get()) });
實際警報[object DOMWindow]
。 誰能指出我正確執行處理程序功能的方向? 可能與事件傳播有關嗎?
您可以使用Function.prototype.call
和Function.prototype.apply
方法來設置Function.prototype.apply
的執行上下文。
$this.bind(settings.endevent, function() {
if(started)
{
handler.call(this);
}
});
這允許您最小化提供給提供的處理程序的接口bind
。
$this.bind(settings.endevent, function() {
if(started)
{
handler.apply(this, arguments);
}
});
現在,處理器將接收事件對象,因為它是第一個參數, this
將被設置的情況下開火的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.