Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

http://stackoverflow.com/questions/14004605/

By: a guest on Dec 23rd, 2012  |  syntax: JavaScript  |  size: 1.09 KB  |  views: 24  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var config = {
  2.     json: {
  3.         baseUrl: "/some/url/$",
  4.         getter: $.getJSON,
  5.         validator: $.isPlainObject
  6.     },
  7.     template: {
  8.         baseUrl: "/some/url/$.mustache",
  9.         getter: $.get,
  10.         validator: function (str) {
  11.             return (/\{\{[a-zA-Z._]*\}\}/).test(str);
  12.         }
  13.     }
  14. };
  15.  
  16. function getItem(itemOrName, type) {
  17.     var result = $.Deferred(), cfg = config[type];
  18.     if (cfg.validator(itemOrName)) {
  19.         result.resolve(itemOrName);
  20.     } else {
  21.         cfg.getter(cfg.baseUrl.replace("$", itemOrName))
  22.         .done(function (data) { result.resolve(data); })
  23.         .fail(function (xhr) { result.reject(xhr); });
  24.     }
  25.     return result.promise();
  26. }
  27.  
  28. var foo = {
  29.     tmplReplaceContent: function (json, tmpl, target) {
  30.         $.when(getItem(json, "json"), getItem(tmpl, "template"))
  31.         .done(function (json, tmpl) {
  32.             var content = Mustache.render(tmpl, json);
  33.             $(target).html(content).hide().fadeIn();
  34.         })
  35.         .fail(function (xhr) {
  36.             // show error message
  37.         });
  38.     }
  39. };