Наверное, я нашел решение.
Вот что я придумал:
// 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 (конечно). Выполнение carUnderControl.goFaster();
с консоли Firebug три раза показывало Текущая скорость: ... сообщение три раза. Последующие выполнения метода goFaster()
показали Увеличение скорости не позволило сообщение.
Это та функциональность, которой я хотел достичь.
Любые рекомендации, как улучшить это очень приветствуются.
Спасибо