I am creating a few DOM elements dynamically like,
var anchorElement = jQuery('<a />',{text:property.text});
var liElement = jQuery('<li />',{"class":"navlink_"+i,id:"navlink_"+i});
anchorElement.on('click',property.fnctn);
liElement.append(anchorElement);
parentID.append(liElement);
Where property is a JSON object.
property.text is the text that I want to put into anchor element. (Works fine)
I want to attach a click event handler to that anchor element.
The function that needs to be bound to that element is specified in JSON and we can access it like
property.fnctn
The following line should bind the event handler to the anchor element.
anchorElement.on('click',property.fnctn);
This was not working so I tried converting it into string like,
anchorElement.on('click',property.fnctn.toString());
No Success…
When I click on this link, the error is logged in the console
The object has no method ‘apply’.
What is the reason…???
I am able to get it working with a slight work around like
anchorElement.attr('onclick',property.fnctn+"()");
Above statement works, but I want to know why .on() API is not working.
Thanks 🙂
AÐitya.
Update:
Youve said that
property.actfnis a string,"paySomeoneClick". It’s best not to use strings for event handlers, use functions instead. If you want the functionpaySomeoneClick, defined in the string, to be called, and if that function is global, you can do this:That works because global functions are properties of the global object, which is available via
windowon browsers, and because of the bracketed notation described below.If the function is on an object you have a reference to, then:
That works because in JavaScript, you can access properties of objects in two ways: Dotted notation with a literal property name (
foo.baraccesses thebarpropety onfoo) and bracketed notation with a string property name (foo["bar"]). They’re equivalent, except of course in the bracketed notation, the string can be the result of an expression, including coming from a property value likeproperty.fnctn.But I would recommend stepping back and refactoring a bit so you’re not passing function names around in strings. Sometimes it’s the right answer, but in my experience, not often. 🙂
Original answer:
(This assumed that
property.fnctnwas a function, not a string. But may be of some use to someone…)The code
will attach the function to the event, but during the call to the function,
thiswill refer to the DOM element, not to yourpropertyobject.To get around that, use jQuery’s
$.proxy:…or ES5’s
Function#bind:…or a closure:
More reading (on my blog):
this