4

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.

AdityaParab
  • 7,024
  • 3
  • 27
  • 40
  • What's the value of `property.fnctn`? – Anthony Grist Jul 26 '12 at 09:30
  • Its a string... I have defined a few functions, names of the respective functions are in property.fnctn I am iterating over JSON array, so every time there is new value.. This is the JSON structure {"item1":{"text":"Wallet","fnctn":"walletClick"}}, {"item2":{"text":"Pay Someone","fnctn":"paySomeoneClick"}}, {"item3":{"text":"Pay Bills","fnctn":"payBillsClick"}} – AdityaParab Jul 26 '12 at 09:31
  • A string containing what? The name of a function or the definition for a function? – Anthony Grist Jul 26 '12 at 09:32
  • @AdityaParab: A *string*?! Don't use strings to hook up event handlers, use functions. – T.J. Crowder Jul 26 '12 at 09:33
  • Name of a function... Sorry I was not aware of shift + enter for new line :) – AdityaParab Jul 26 '12 at 09:34
  • @T.J.Crowder He said it was in a JSON object, which made me curious. I'm by no means an expert but I didn't think a JSON property could be an actual function. – Anthony Grist Jul 26 '12 at 09:34
  • @AnthonyGrist: It can't be, but that doesn't mean you should use a string for an event handler. Just that you need to do a bit more work. :-) – T.J. Crowder Jul 26 '12 at 09:35
  • @T.J. The function that needs to be invoked will different every time.. So I am getting the appropriate function name from server in JSON format... – AdityaParab Jul 26 '12 at 09:35
  • and I want to bind "that" function every time the script is run.. – AdityaParab Jul 26 '12 at 09:37
  • @AdityaParab: I would recommend refactoring that (using a parameter instead, for instance), but I've updated my answer to work with what you're currently doing. – T.J. Crowder Jul 26 '12 at 09:37

1 Answers1

8

Update:

Youve said that property.actfn is a string, "paySomeoneClick". It's best not to use strings for event handlers, use functions instead. If you want the function paySomeoneClick, defined in the string, to be called, and if that function is global, you can do this:

anchorElement.on('click',function(event) {
    return window[property.fnctn](event);
});

That works because global functions are properties of the global object, which is available via window on browsers, and because of the bracketed notation described below.

If the function is on an object you have a reference to, then:

anchorElement.on('click',function(event) {
    return theObject[property.fnctn](event);
});

That works because in JavaScript, you can access properties of objects in two ways: Dotted notation with a literal property name (foo.bar accesses the bar propety on foo) 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 like property.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.fnctn was a function, not a string. But may be of some use to someone...)

The code

anchorElement.on('click',property.fnctn);

will attach the function to the event, but during the call to the function, this will refer to the DOM element, not to your property object.

To get around that, use jQuery's $.proxy:

anchorElement.on('click',$.proxy(property.fnctn, property));

...or ES5's Function#bind:

anchorElement.on('click',property.fnctn.bind(property));

...or a closure:

anchorElement.on('click',function(event) {
    return property.fnctn(event);
});

More reading (on my blog):

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks T.J ! Got it loud and clear... May be I need to talk with my project manager to consider redesigning this approach... :) Alright, is there any reason as why not to use strings as event handlers? (Just curious about it) – AdityaParab Jul 26 '12 at 09:41
  • 2
    @AdityaParab: Re using strings to assign to `click` handlers, it's not a good idea because it requires the JavaScript parser to fire up and parse the string, and it obscures what's going on. Re passing function names around, it conflates *code* and *data*, which is usually (but not always!) less than ideal. If you can abstract that a bit, pass around information that your code then interprets to say "oh, that means we should call this function", it's usually best. But there can be real arguments for just passing a function name around, when server code is sending client code a message. Best, – T.J. Crowder Jul 26 '12 at 09:44
  • @T.J.Crowder Okay Thanks for reply.. sure u can delete it. do u hav any reference to help me? – gprathour Jul 26 '12 at 09:46