I am trying to associate a function with an onclick binding. I do not use traditional jQuery bind / live / on / whatever, because I have other scripts that stop event propagation (this sucks, I know).
To associate a function with the onclick attribute, I pass the JSON object to the module as follows:
function foo() { alert('foo') } $('document').ready(function() { var options = { opt1: 'fooID', opt2: 'barID', json: mightyJSON, actions: [ { url: 'contact/_id_/edit', text: "Edit", iconPath: 'edit.png' }, { url: '#', onClick: foo, text: "Delete", iconPath: 'delete.png' } ] }; var trolol = myModule.configure(options); });
As you can see, a function called "foo" is passed through the "onClick" JSON property. The function is defined above the object.
In "myModule" I create an anchor tag as follows:
var buildLinks = function(objectID) { var linksNbr = actions.length; var link, cssClass; for (var i = 0; i < linksNbr; i++) { // Adding the object ID to the URL link = actions[i].url.replace('_id_', objectID); cssClass = actions[i].cssClass || ''; var $link = $(document.createElement('a')).attr('onClick', actions[i].onClick) .attr('href', link) .attr('title', actions[i].text) .addClass(cssClass) .text('foo'); } return $link.html(); };
The fact is that, as you can expect, "foo" is executed when the script is parsed and only there. "Onclick" doesn't even work after.
I can describe this as onClick: 'foo()' . The onclick job works, but it also does the parsing, and this, in my opinion, is very ugly.
I would still be able to pass it like this onClick: foo , but it worked correctly (i.e. it was not executed at boot time, but only when clicked.
It should work with jQuery 1.4.4, unfortunately.