Question

I'm creating a custom JS object. This object performs some action. I want to be able to notify consumer of the object (by triggering custom events) that action will be performed and action is already performed. (This model of behavior is known in ASP.NET where controls have onBeforeAction and onAfterAction events).
The tricky part is that I would like consumer to be able to stop/interrupt the event sequence.

Here is an algorithm (in Human#) of desired behaviour:

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

Having this functionality in my object would allow consumer to do something like this:

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

Any ideas on how to implement a 'controllable' event sequence would be great.
Thanks in advance.
// R

Was it helpful?

Solution 2

I guess I have found solution.
Here's what I came up with:

// 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"
    }
}

Then some consumer could act like this:

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

I've run this in FireFox with Firebug (of course). Executing carUnderControl.goFaster(); from Firebug's console for three times showed Current speed: ... message three times. Subsequent executions of goFaster() method showed Speed increase prevented message.

That's the functionality I wanted to achieve.
Any recommendations how to improve this are very much welcome.

Thanks

OTHER TIPS

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

Replace click with your custom event name :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top