PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/practicals/qunit-koans/js/ext/template.js

https://github.com/donnut/backbone-fundamentals
JavaScript | 36 lines | 22 code | 6 blank | 8 comment | 3 complexity | e4c863f6440263d72e84a7f57eae09af MD5 | raw file
  1. (function($) {
  2. var cache = {};
  3. function _render(elt, template, data, callback) {
  4. var data = data || {},
  5. callback = callback || function() {},
  6. html = template(data);
  7. elt.append(html);
  8. callback();
  9. }
  10. /**
  11. * Fetches the Underscore.js template at the given path,
  12. * processes it with the provided data object, and appends the
  13. * resulting html to the matched DOM elements.
  14. *
  15. * Templates will only be fetched once from the server,
  16. * preprocessed template are cached in the DOM.
  17. */
  18. $.fn.template = function(path, obj, callback) {
  19. var self = this;
  20. if (cache[path]) {
  21. _render(self, cache[path], obj, callback);
  22. return self;
  23. }
  24. $.get(path, function(data) {
  25. cache[path] = _.template(data);
  26. _render(self, cache[path], obj, callback);
  27. });
  28. return self;
  29. };
  30. })(jQuery);