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

3 comments:

d.wachss 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

smallawei said...

情趣用品爽翻天,情趣爽翻天情人趣味艾蜜莉,情人趣味艾蜜莉,情色貼圖,情趣商品,情趣用品店,
丁字褲,SM,情趣,情趣用品,情趣味用品,,
充氣情人趣味,
G點,按摩棒,轉珠按摩棒,變頻跳蛋,跳蛋,無線跳蛋,

情人節禮物,情人趣味用品珠,情人趣味用品
情人趣味用品轉,情人趣味用品娃,
震動環,潤滑液,情趣禮物,情趣玩具,威而柔,精油,逼真按摩棒,數位按摩棒,

飛機杯,男用強精長軟質套,男用強精短軟質套,充氣娃娃,自慰套,自慰套,情趣娃娃,自慰器,電動自慰器,充氣娃娃,
情人趣味用品愛蜜莉,情人趣味用品液
薄紗情人趣味,煙火,

Powered by Blogger.