Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I use something similar when rendering form fields dynamically.

    draw_checkbox = function() {}
    draw_radio    = function() {}
    draw_select   = function() {}

    draw_field = function(type) {
      this['draw_' + type]();
    }

    draw_list = function(list) {
       for(i = 0; i < list.length; i++)
         draw_field(list[i].type);
    }
For sake of simplicity, I did not include the code to verify that type is proper and parameters sent to each function.


This is probably the part I dislike most about ruby (I know this is JS). There are some places where this trick makes a painful piece of code go away, so I appreciate why it was selected. The problem is that you now have no reference to draw_checkbox being used in your entire code base and when someone else is refactoring, they think they can remove it.

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.


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


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.


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: