Ricardo Martins
Ricardo Martins

Reputation: 6003

How do I add a listener to JavaScript Object variable?

I have an object generated by this code, but I can only use it when its obj.ready property is == true. I can use only pure JavaScript or Prototypejs. It script is inserted as source (< script src=...).

Is there a way to detect when the object is ready to use? I tried to put observer on dom:loaded, but it didn't work.

I use

PagSeguroDirectPayment.setSessionId('someTextHere');
PagSeguroDirectPayment.getSenderHash(); 

The second line doesnt work because the object is not ready yet.

Any help is appreciated.

Upvotes: 0

Views: 183

Answers (1)

c-smile
c-smile

Reputation: 27460

If you have no infrastructure of events there then the only option is to do polling:

function whenReady(obj, callback) {
  var iid = setInterval(function() {
    if(obj.ready) {
      callback();
      clearInterval(iid);
    }
  }, 20);
}

And to use it as:

PagSeguroDirectPayment.setSessionId('someTextHere');
whenReady(PagSeguroDirectPayment, function() {
  PagSeguroDirectPayment.getSenderHash(); 
}); 

Upvotes: 2

Related Questions