Re:Using Dispatch Tables to Avoid Conditionals in JavaScript
by taf2 on Monday May 13, 2013 @10:09AM
(#5698712)
yeah, i kinda agree.. in this case I'd have done something more like:
function Renderer() {}
Renderer.prototype = {
draw: {
checkbox: function() {},
radio: function() {},
select: function() {},
field: function(type) {
this[type]();
},
list: function(items) {
return items.map(function(item) {
return this.field(item.type)
});
}
}
}
Perhaps I'm just comment trolling though - totally depends on how the code would have been used...
Re:Using Dispatch Tables to Avoid Conditionals in JavaScript
by chime on Monday May 13, 2013 @12:15PM
(#5699525)
Actually my code ends up looking pretty much like yours. I use CoffeeScript and was writing a simplified JS equivalent off the top of my head since this post was about JS. Similar to your Renderer, I have a DrawForm class that iterates through DrawField class objects which provide the checkbox(), radio() etc. methods.
My point was that in the end, you get to do dynamic function instantiation, which is pretty awesome in JS.
Re:Using Dispatch Tables to Avoid Conditionals in JavaScript
by mdpye on Monday May 13, 2013 @10:13AM
(#5698734)
I'd prefer to see the functions put in a dictionary and invoked from there rather than named individually in the local scope, easier to see at least what you have to look for when you want to see if they're referenced, and you'd have dict[item] rather than "dict" + item.
Edit: taf2's seems more idiomatic, js is not my first language.
Personally, I would never elect to go this route because it only introduces overhead for refactoring and code maintenance. I would rather see a mess of procedural code, than some silly clever little tricks that will trip up all the new people.