2011-08-06 42 views
0

我有一個自定義類,看起來像:事件回調,使用變量事件名稱。可能?

function myClass(){ 
    var thing; 
    var thingtype; 
} 

我使用的是第三方庫創建和管理「A'型‘的事情’,以及第二第三方庫創建和管理'B'類的東西。

當我的A或B類型的東西加載時,我想執行一個回調。

假設第一個第三方庫在A類事物加載時廣播'onLoad'事件,而第二個庫在加載B類事件時廣播'onReady'事件。

我可以說:

if (thingtype=='A'){ 
    thing.onLoad(function(){alert ("my callback");}) 
} 
if (thingtype=='B'){ 
    thing.onReady(function(){alert ("my callback");}); 
} 

我的問題: 是否可以用變量的事件名稱,類似:

if (thingtype=='A'){ 
    myLoadEvent = 'onLoad'; 
} 
if (thingtype=='B'){ 
    myLoadEvent = 'onReady'; 
} 
thing.myLoadEvent(function(){alert ("my callback");}); 

非常感謝!

回答

0

onLoadonReadything對象的正常屬性。訪問使用其字符串名稱的任何屬性,使用obj[x]來查找值:

thing[myLoadEvent](function(){alert ("my callback");}); 

這裏有一個簡單的例子來說明這一概念:

var foo = { 
    bar: function() { return 'baz'; } 
}; 

console.log(foo.bar());     // => 'baz' 
console.log(foo['bar']());    // => 'baz' 
console.log(foo.bar() === foo['bar']()); // => true 
+0

謝謝。正是我需要的! – moondog