简体   繁体   中英

javascript function name as string

There is an external library which is sending some responses with javascript callbacks passed as string function name. I would like to be able to execute a callback function whenever the function callback is called:

function LibController(myCallback) {
  this.libObject = new ThirdPartyLibrary("onTPLCallback");
}

window.onTPLCallback = function () {
  // Call to myCallback() in here
};

function AnotherObject() {
  this.myLibController = new LibController(function () {
    // Callback stuff here
  });
}



// Library object emulation
function ThirdPartyLibrary(callback) {
  var sc = document.createElement('script');
  sc.innerHTML = 'javascript:' + callback + '();';
  document.head.appendChild(sc);
}

Is it possible? (jQuery is not available)

You could try by placing the window.onTPLCallback inside LibController constructor (it has to be placed before ThirtPartyLibrary is constructed):

function LibController(myCallback) {
  window.onTPLCallback = function () {
    myCallback();
  };

  this.libObject = new ThirdPartyLibrary("onTPLCallback");
}

function AnotherObject() {
  this.myLibController = new LibController(function () {
    // Callback stuff here
  });
}



// Library object emulation
function ThirdPartyLibrary(callback) {
  var sc = document.createElement('script');
  sc.innerHTML = 'javascript:' + callback + '();';
  document.head.appendChild(sc);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM