Nizzy
Nizzy

Reputation: 1889

Event handler cannot access Object method in JavaScript

How can I access util.log() method from a static html event handler?

In other words, when I click the checkbox, I like to call util.log method.

onclick="util.log(\'hey\')" <-- how to rewrite the event function here?

I know all the answers are correct down here but is it possible to access local methods while insert the html into innerHTML?

thank you

var utilities = function() {
 var util = this;

 util.log = function(msg){
  alert(msg);
 };

 var p = document.createElement('p');
 p.innerHTML = '<input type="checkbox" onclick="util.log(\'hey\')" value="1">Check me'; 
 // this part has to be plain html, because there is this table generator class 
 // will insert this to cell as innerHTML. That's why I can't change the table class. 
};

Upvotes: 1

Views: 1072

Answers (2)

Ben Zotto
Ben Zotto

Reputation: 71008

Your util object is not in the global scope; it's hidden inside the utilities object. The click handler will run in the scope of the global object, which is why it can't see util at all.

If you can't change the way the HTML strings are created, then you'll need to declare util outside the utilities function, in other words, just this in the page:

 var util = {};
 util.log = function(msg){
  alert(msg);
 };

 var p = document.createElement('p');
 p.innerHTML = '<input type="checkbox" onclick="util.log(\'hey\')" value="1">Check me'; // this part is a legacy code and I have no control over to rewrite it as HTMLObjectElement way

Upvotes: 2

Hogan
Hogan

Reputation: 70513

try this javascript instead:

var util = {
 log : function(msg){
  alert(msg);
 };
};

Upvotes: 1

Related Questions