4

I Have this JavaScript code:

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
    this.runtime = runtime;
};
(function() {
 function initialize_events(result) {
  alert(result);
 }
})();
<button onclick="initialize_events('Test Result');">Send Result</button>

how to run 'initialize_events' function from html by clicking on button?

I don't have access to editing JavaScript file.

ChrisDunne
  • 15
  • 5
Milad Mohammadi
  • 105
  • 1
  • 3
  • 12
  • 6
    Sadly you cant. the function is only declared inside its own scope. You cant access ist without editing the js file. – Bellian Jul 26 '17 at 09:06
  • 1
    Didn't seen you don't have access to js file. You can't access the function declared in a private scope (inside IIFE function). – n1kkou Jul 26 '17 at 09:07

1 Answers1

13

i dont have access to editing js file.

Then you can't, full stop. It's entirely private to the anonymous IIFE* that encloses it. You'd have to expose it as a global in order to use it with an onxyz-attribute-style event handler (and that would require modifying the JavaScript code). It's one of the many reasons not to use them.

Since you can't do it without modifying the JavaScript, I'm going to assume you overcome that limitation and suggest what to do when/if you can modify the JavaScript:

Have that IIFE hook up the button, and use a data-* attribute if you need button-specific information to pass it:

var cr = {};
cr.plugins_ = {};
cr.runtime = null;

cr.plugins_.Vinoos_Markets = function(runtime) {
  this.runtime = runtime;
};
(function() {
  function initialize_events(result) {
    alert(result);
  }
  document.getElementById("send-result").addEventListener("click", function() {
    initialize_events(this.getAttribute("data-result"));
  }, false);
}());
<button id="send-result" data-result="Test Result">Send Result</button>

Notes:

  • If you need to support obsolete browsers without addEventListener (such as IE8, which is sadly still a requirement for many), see this answer for a cross-browser event hooking function.
  • If you have the data in the IIFE rather than the button, you can just use it directly rather than using a data-* attribute.
  • Giving the button an ID and using getElementById is just an example; in practice, anything that lets you identify the button is all you need. You can look up using a full CSS selector via document.querySelector.

* IIFE = immediately-invoked function expression, e.g., (function() { /*...*/})(); (Also sometimes called an "inline-invoked function expression." Also sometimes erroneously called a "self-invoking function," but it isn't; it's invoked by the code defining it, not by the function itself.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875