Search code examples
backbone.jshelperorganizationcode-organization

Place of the helper functions in Backbone


I've got some functions like this:

function killOrphans(str) {
    return str.replace(/\s([\dwuioaz]{1})\s/gi, ' $1\u00a0');
}

which is generally a helper function to remove single letter words (orphans) from the end of a line (Polish typography demands to do this).

Question: how do you treat a library of such functions? A module in the global scope? extending jQuery? Extending the prototypes of String, Array etc.? (I don't think it's a good idea...). I think I'll go in the direction of underscore and create a module, but I'd be glad to hear real life examples of your way to do it.

Adam


Solution

  • In my project, I've used a variety of strategies for helper functions.

    Extra methods on a view or a model.

    var MyView = Backbone.View.extend({
      initialize: function(){...},
      render: function(){...},
      helper: function(){...}
    });
    

    Use a helper module.

    var myHelpers = {
      foo: function(){...},
      bar: function(){...},
      baz: function(){...}
    };
    

    Extend an existing lib.

    jQuery.fn.foo = function(){...};
    

    Use an IIFE (best for functions you'd like to keep private)

    var MyView = Backbone.View.extend({
      initialize: function(){...},
      render: function(){...},
      myMethod: (function(){
        function helper(){...}
        return function(){
          // do stuff here, using helper()
        }
      })()
    });
    

    Also, if you're not working in node.js which automatically provides a module system, it's worth using some strategy, such as browserify or requirejs, to export and import modules in a sane way, rather than having everything hang off the global namespace.