Another JavaScript function invocation method

these day i find my self write a lot of JavaScript while doing client centric application, and i try to make my code faster, better understood and smaller.

Lets the following example that i needed to call hide method when a flag was false and show method when it was true:

var flag = ...;
var jqo = $('#someobject');
if (flag)
    jqo.show();
else
    jqo.hide();

another nicer (i like to think so) way:

var flag = ...;
var jqo = $('#someobject');
jqo[flag ? 'show' : 'hide']();

What do you think?
Another JavaScript function invocation method Another JavaScript function invocation method Reviewed by Ran Davidovitz on 1:22 PM Rating: 5

2 comments:

Danny W said...

jqo.toggle(flag) should do what you want, more compactly.
(the trick of invoking a method as object['name']() rather than object.name() is still often useful)
--Danny

Ran Davidovitz said...

Thanks for adding the reference to Toggele action also, important to remember that Toggle is a good solution if you need a simple action of hide/show without logic (meaning static change), i published my solution because lots of time you need the action to be based on a logic

thanks for sharing

Powered by Blogger.