jQuery OOP technique confusion
<p>I'm looking at <a href="http://jamietalbot.com/2010/08/22/object-oriented-jquery-plugins/" rel="nofollow">Jamie Talbot's technique for OOP in jQuery</a>. I pretty much understand this for the most part, however I'm getting slightly lost when trying to understand the logic for this:</p>

<pre><code>result = $(result);

        var template = result[0];
        if (template) 
        {
            for (var i in template)
            {
                if (typeof (template[i]) == 'function') 
                {
                    result[i] = function()
                    {
                        this.each(function() 
                        {
                            this[i]();
                        });
                    };
                }
            }
        }
</code></pre>

<p>I understand up to the <code>if (typeof (template[i]) == 'function')</code> block, that the code is looking at each public method that is declared in the plugin, but after that it boggles me.</p>

<p>Is there any chance somebody could step by step me through this?</p>

<p>Here's Jamie's original code.</p>

<pre><code>(function($) {
  $.fn.encapsulatedPlugin = function(plugin, definition, objects, options) {
    var result = [];
    objects.each(function() {
      var element = $(this);

      if (!element.data(plugin)) {
        // Initialise
        var instance = new definition(this, options);

        // Store the new functions in a validation data object.
        element.data(plugin, instance);
      }
      result.push(element.data(plugin));
    });

    // We now have a set of plugin instances.
    result = $(result);

    // Take the public functions from the definition and make them available across the set.
    var template = result[0];
    if (template) {
      for ( var i in template) {
        if (typeof (template[i]) == 'function') {
          result[i] = function() {
            this.each(function() {
              this[i]();
            });
          };
        }
      }
    }

    // Finally mix-in a convenient reference back to the objects, to allow for chaining.
    result.$ = objects;

    return result;
  };

})(jQuery);
</code></pre>
