2012-12-29 41 views
0

我有这样的代码针对JavaScript应用程序的设置“国家机器”:绑定回调参数

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

我没有在这一点上理解什么是其中当前参数绑定功能来自(即:this.bind("change", function(e, current){...})。我尝试将它记录在萤火虫控制台面板上,它似乎是StateMachine.fn.add函数中的控制器参数。你能告诉我这个参数来自哪里吗? 谢谢。

+0

这将是'controller',因为它是在触发时传递给[.bind()](http://api.jquery.com/bind/)的'handler'参数! – adeneo

+0

你能解释一下吗,我没有明白你的意思。 – petwho

回答

1

据我了解,您指定的第二个参数传递给您的事件回调位置:

this.trigger("change", controller); 

jQuery的触发方法调用所有绑定的功能,传递事件对象作为第一个参数(总),然后,在它之后,将事件名称后传递给.trigger()方法的所有参数。