Set element onclick from JavaScript string

I have some code which generates HTML with something like this:

function foo(onclick:string):HTMLElement {
    return parseHTML('<input type="button" onclick="' + escapeHTML(onclick) + '" />');
}

which I want to migrate to code like this:

function foo(onclick:string):HTMLElement {
   var input = document.createElement('input');
   input.type = 'button';
   input.onclick = onclick; // <= is this correct?
   return input;
}

Besides the fact that I should be using a real JavaScript function instead of a string of code, what is the correct way to set the onclick attribute using the passed JavaScript string so that it works the same way as it did when generating HTML with the onclick attribute?

edit:

The input.onclick property the code above is setting is supposed to be a real JavaScript function object, not a string of JavaScript (according to Mozilla docs) so the code above is not correct.

I am trying to change the implementation of foo() without needing the change the usages. They need to be able to continue passing in a string of JavaScript.

Answers


The solution turned out to be to convert the JavaScript string into a function object with a single parameter using the Function constructor:

function foo(onclick:string):HTMLElement {
    var input = document.createElement('input');
    input.type = 'button';
    input.onclick = new Function('event', onclick);
    return input;
}

This gives the passed JavaScript code the exact same environment as though it were written in the onclick="..." attribute in HTML:

  • The event variable will be set to the appropriate Event object
  • The arguments will contain a single argument which is the Event object
  • The this object will be the HTML element itself
  • The code will run in it's own scope with the global scope next in the scope chain

The solution comes from http://perfectionkills.com/global-eval-what-are-the-options/

This would also work:

// ...
input.onclick = (1,eval)('(function(event){' + onclick + '})');
// ...

Need Your Help

Galaxy S3 memory leak using createBitmap in very simple code

bitmap galaxy

I have been trying to create a bitmap, create a canvas with that bitmap, and then pass it to my onDraw method in an imageView. During this process I noticed that the simple application was leaking ...

How to have an asp.net ajax control automatically reference css files

css asp.net-ajax user-controls webusercontrols

I was wondering if its possible to have an ASP.NET AJAX custom usercontrol 'register' its use of CSS files like it does with JS files. ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.