質問

カスタム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);
    });

FirefoxでFirebugでこれを実行しています(もちろん)。実行 carUnderControl.goFaster(); FireBugのコンソールから3回表示されます 現在の速度:... メッセージを3回メッセージ。後続の実行 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