开发者

Event callback, using variable event-name. possible?

I have a custom class that looks like:

开发者_JAVA技巧
function myClass(){
  var thing;
  var thingtype;
}

I am using a third-party library to create and manage 'A'-type 'things', and a second third-party library to create and manage 'B'-type things.

When my A or B type thing loads, I would like to execute a callback.

Suppose the first third-party library broadcasts an onLoad event when an A-type thing loads, and the second library broadcasts an onReady event when a B-type thing loads.

I could say:

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

My question: Is it possible to instead use a variable for the event-name, something like:

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


onLoad and onReady are normal properties of the thing object. To access any property using its string name, use obj[x] to look up that value:

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

Here's a simpler example to illustrate this concept:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜