Best practices, scoping, not taking up namespace room...

Best practices, scoping, not taking up namespace room...

Just got into jQuery and I am trying to write a wrapper for some existing templating code. I would like to follow best practices from the beginning, so this future jQuery plugins I write aren't a pile of poo.

I have been trying to follow some of the online tutorials, but none I've found seem to cover exactly what I want to do; probably more a reflection on my Googling abilities than anything.... :o)

Anyway, the base templating code has tow main functions; you call a template creation function on an element on page load that stores that element as a template and removes it from the DOM. Then, later, you call a populate function that fills the template with data and re-inserts it into the DOM. This is obviously used mainly with AJAX requests.

The plugin wrapper I have come up with (which works) is as follows:

  1. (function($) 
  2.   $.fn.hTemplate = function(props) 
  3. {
  4. var $this = this;
  5. // For each selected element, if the template has not already been created, create it
  6. $this.each(function(index) 
  7. {
  8. if(!this.__hTemplate)
  9. this.__hTemplate = new HTemplates.Template(this);
  10. });
  11. // The populate function; for each element, populate the template if it exists
  12. this.populate = function(data) 
  13. {
  14. // 
  15. $this.each(function(index) 
  16. {
  17. if(this.__hTemplate)
  18. this.__hTemplate.populate(data)
  19. });
  20.  
  21. // Return jQuery object for chaining
  22. return $this; 
  23. };
  24. // Return jQuery object for chaining
  25. return $this; 
  26. };
  27.  })(jQuery);
This I am calling as follows:

  1. $('.testTemplate').hTemplate();
  2. $('.testTemplate').hTemplate().populate(data);

Now, to me, the populate call looks odd, with the hTemplate().populate(); however, I have found posts suggesting this as the way forward.

So my questions is really, am I doing it right, and if not, what should I be doing?

More specifically, is it good practice to have the main hTemplate() call do these two tasks with the check in the each()? Is it good practice to store the template object against the element as above in __hTemplate?

Any suggestions would be appreciated!

P.S. How do I maintain the code indentation in the forum?!