javascript创建类事件

Kev*_*Pei 2 javascript class

如何为javascript类创建自定义事件?
示例代码

function somefunction(url){
   this.h_world = function(){/*some random code to do*/ };
}

var hw = new somefunction();
Run Code Online (Sandbox Code Playgroud)

现在,举一个非常简单的例子,如何在hw.h_world完成执行并为其返回一些数据时为此创建一个自定义事件处理程序?

例如

var hw = new somefunction();
hw.h_world();
hw.finished_h_world = function(somedata){
  alert(somedata);
}
Run Code Online (Sandbox Code Playgroud)

Rém*_*ton 5

你需要的是一个回调函数:

function somefunction(url){
   this.h_world = function(callback){
      var somedata = 'some data';
      callback(somedata);
   };
}
Run Code Online (Sandbox Code Playgroud)

然后:

var hw = new somefunction();
hw.h_world(function(somedata){
    alert(somedata); // Will alert 'some data';
});
Run Code Online (Sandbox Code Playgroud)

这是一个jsfiddle:http://jsfiddle.net/remibreton/xzeEd/