Khanh Tran
Khanh Tran

Reputation: 1826

bind callback parameter

I have this code to set "State Machine" in view of a javascript application:

    var Events = {
      bind: function(){
        if ( !this.o ) this.o = $({});
            this.o.bind(arguments[0], arguments[1])
      },

      trigger: function(){
        if ( !this.o ) this.o = $({});
            this.o.trigger(arguments[0], arguments[1])
      }
    };

    var StateMachine = function(){};
    StateMachine.fn  = StateMachine.prototype;
    $.extend(StateMachine.fn, Events);

    StateMachine.fn.add = function(controller){
      this.bind("change", function(e, current){
        console.log(current);
        if (controller == current)
          controller.activate();
        else
          controller.deactivate();
      });

      controller.active = $.proxy(function(){
        this.trigger("change", controller);
      }, this);
    };

    var con1 = {
      activate: function(){ 
        console.log("controller 1 activated");
      },
      deactivate: function(){ 
        console.log("controller 1 deactivated");
      }
    };

    var sm = new StateMachine;
    sm.add(con1);        
    con1.active();

What I don't understand at this point is where the current parameter in bind function comes from (That is: this.bind("change", function(e, current){...}). I try to log it on firebug console panel and it seems to be the controller parameter in StateMachine.fn.add function. Could you tell me where this parameter comes from? Thank you.

Upvotes: 0

Views: 306

Answers (1)

user1936059
user1936059

Reputation:

As far as I understand, you specified the second argument to be passed to you event callback here:

this.trigger("change", controller);

jQuery's trigger method will call all binded functions, passing the Event object as the first argument (always), and then, after it, all the arguments you passed to .trigger() method after the name of event.

Upvotes: 1

Related Questions