2012-03-12 69 views
2

如何爲JavaScript類創建自定義事件?
示例代碼javascript創建類事件

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

var hw = new somefunction(); 

現在,一個很簡單的例子,我怎麼創建這個自定義事件處理函數時hw.h_world已經執行完畢,並用它返回一些數據?

例如

var hw = new somefunction(); 
hw.h_world(); 
hw.finished_h_world = function(somedata){ 
    alert(somedata); 
} 
+0

號事件是由簡單的執行產生的JavaScript代碼(除了屬性「監視」設置中的Firefox中的某些特殊行爲外)。 – Pointy 2012-03-12 15:59:12

回答

2

你可以傳遞一個回調函數h_world功能並執行它在它的

function somefunction(url){ 
    this.h_world = function(cb){ 
     //do some operation 
     if (cb && typeof cb === 'function') { 
     cb(); 
     //cb.call(this, args1, arg2...); //execute callback in scope of current object 
     } 
    }; 
} 

,或者你可以添加一個功能到您的類像完成這個

function somefunction(url){ 
    this.h_world = function(){ 
     //do operation 
     this.h_world_finish(parameters); 
    }; 
    this.h_world_finish = function() {}; 
} 

var obj = new someFunction(url); 
obj.h_world_finish = function (arg) { 
    alert("finished h_world"); 
}; 
obj.h_world(); 
+0

這實現了我一直在尋找的東西。謝謝 – 2012-03-12 16:26:16

+0

這個差異是怎麼的...算了吧。 – 2012-03-12 19:02:52

5

你需要的是一個回調函數:

function somefunction(url){ 
    this.h_world = function(callback){ 
     var somedata = 'some data'; 
     callback(somedata); 
    }; 
} 

然後:

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

下面是一個的jsfiddle:http://jsfiddle.net/remibreton/xzeEd/