2011-03-14 75 views
0

我正在創建一個自定義JS對象。該對象執行一些action。 我希望能夠通知消費者對象(通過觸發自定義事件)action將被執行action已被執行。 (這種行爲模式在ASP.NET中已知,其中控件具有onBeforeActiononAfterAction事件)。
棘手的部分是我希望消費者能夠停止/中斷事件序列。jQuery自定義事件序列

這是需要的行爲的算法(在人類#):

 
this.trigger('onBeforeAction'); 
if (!onBeforeAction.wasCanceled){ 
    this.doAction(); 
    this.trigger('onAfterAction'); 
} 

有我的目標該功能將允許消費者做這樣的事情:

 
$(myIntance).bind('onBeforeAction', function(){ 
    if (!someCondition.satisfied) 
    return false; 
    return true; 
}); 
$(myIntance).bind('onAfterAction', function(){ 
    // respond to action here 
}); 

如何任何想法實施「可控」事件序列會很好。
在此先感謝。
// [R

回答

0

單擊我想我已經找到了解決方案。
這就是我想出了:

// my object 
function Car(){ 
    this.currentSpeed = 0; 
} 

Car.prototype.goFaster = function(){ 
    var event = $.Event('beforeSpeedIncrease'); 
    $(this).trigger(event); // notify "onBeforeAction" 
    if (!event.isDefaultPrevented()){ 
     this.currentSpeed += 10; // actual action 
     $(this).trigger('afterSpeedIncreased'); // notify "onAfterAction" 
    } 
} 

那麼一些消費者可以充當這樣的:

var speedLimit = 30; 

var carUnderControl = new Car(); 

$(carUnderControl) 
    .bind('beforeSpeedIncrease', function(e){ 
     if (carUnderControl.currentSpeed >= speedLimit){ 
      e.preventDefault(); 
      console.log('Speed increase prevented, current speed: ' + carUnderControl.currentSpeed); 
     } 
    }) 
    .bind('afterSpeedIncreased', function(){ 
     console.log('Current speed: ' + carUnderControl.currentSpeed); 
    }); 

我已經在Firefox使用Firebug運行此(當然)。從Firebug的控制檯執行carUnderControl.goFaster();三次顯示當前速度:...消息三次。 goFaster()方法後續執行顯示速度增加阻止消息。

這就是我想達到的功能。
任何建議如何改善這是非常受歡迎的。

感謝

0
(function ($) { 
    var origin = $.fn.click; 
    $.fn.click = function(event) { 
    //before function 
    origin.call(this, event); 
    //after function 
    // remember to use return as this could help with jq chainability 
    }; 
})(jQuery); 

替換您的自定義事件名稱:)

+0

能否請您詳細闡述更多關於如何我的對象將被通知onBeforeAction處理程序返回false,它不應該提高後續onAfterAction事件?對不起,我只是看不到整幅圖片 – Ramunas 2011-03-14 18:54:53