1

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. 
};
2
  • Do you want an alert saying "hey" when you click the checkbox? Commented Feb 5, 2010 at 2:30
  • yes, but eventually, how to call an object method from hard-coded events? Commented Feb 5, 2010 at 2:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

try this javascript instead:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.