On Oct 9, 2011, at 5:17 AM, T.J. Crowder wrote: > Hi, > > On Oct 8, 6:30 pm, Walter Lee Davis <wa...@wdstudio.com> wrote: >> What's a more idiomatic way to write this: >> >> Element.addMethods({ >> toggleClassName: function(element, className){ >> var element = $(element); >> (element.hasClassName(className)) ? >> element.removeClassName(className) : element.addClassName(className); >> return element; >> } >> >> }); >> >> This works, but it's got that really long line in the middle. How do you do >> what PHP calls a "variable variable" in JavaScript to execute the correct >> method (add/remove) based on the input without writing it all out long-hand? >> >> Walter > > You are aware that Prototype *has* `toggleClassName` already[1], > right? And in fact, I think the current implementation of it answers > your question about "variable variables": > > toggleClassName: function(element, className) { > if (!(element = $(element))) return; > return Element[Element.hasClassName(element, className) ? > 'removeClassName' : 'addClassName'](element, className); > }, > > That works because as you probably know, you can refer to an object > property using a literal with dotted syntax: > > x = obj.foo; > > ...or with a string using bracketed syntax: > > x = obj['foo']; > > The latter opens up the possibility of using an expression for the > string: > > x = obj[flag ? 'foo' : 'bar']; > > And of course, what we think of as methods aren't really methods at > all[2], they're just functions assigned to properties, and so: > > obj[flag ? 'foo' : 'bar'](); > > ...will call `obj.foo()` or `obj.bar()` depending on the value of > `flag`. That's what the Prototype version of `toggleClassName` does, > it calls `removeClassName` or `addClassName` based on the result of > calling `hasClassName`. > > This form of "variable variables" only works with object properties, > but I find that it applies in 99% of the situations I'd want it. > > [1] http://api.prototypejs.org/dom/Element/toggleClassName/ > [2] http://blog.niftysnippets.org/2008/03/mythical-methods.html > > HTH, > -- > T.J. Crowder > Independent Software Engineer > tj / crowder software / com > www / crowder software / com
Wow. FacePalm! Thanks very much, I'd been re-doing this long-hand since 1.4, never realized it was "native". Walter -- You received this message because you are subscribed to the Google Groups "Prototype & script.aculo.us" group. To post to this group, send email to prototype-scriptaculous@googlegroups.com. To unsubscribe from this group, send email to prototype-scriptaculous+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/prototype-scriptaculous?hl=en.