我正在创建一个自定义JS对象。此对象执行一些 action。我希望能够通知消费者对象(通过触发自定义事件) action 将被执行 action 已经执行。 (这种行为模型在控制中有ASP.NET中已知 onBeforeActiononAfterAction 事件)。
棘手的部分是,我希望消费者能够停止/中断事件序列。

这是一种理想行为的算法(人类#):

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

有帮助吗?

解决方案 2

我想我找到了解决方案。
这是我想到的:

// 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);
    });

我已经用Firebug(当然)在Firefox中运行此操作。执行 carUnderControl.goFaster(); 从Firebug的控制台出现了三遍 现在的速度: ... 消息三次。后续执行 goFaster() 方法显示 速度增加了 信息。

那就是我想实现的功能。
任何建议如何改进这一点都是非常欢迎的。

谢谢

其他提示

(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);

用您的自定义事件名称替换点击:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top