templating.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. define(["jquery", "util", "peers", "windowing", "session"], function ($, util, peers, windowing, session) {
  5. var assert = util.assert;
  6. var templating = util.Module("templating");
  7. templating.clone = function (templateId) {
  8. templateId = "#togetherjs-template-" + templateId;
  9. var template = $(templateId);
  10. assert(template.length, "No template found with id:", templateId);
  11. template = template.clone();
  12. template.attr("id", null);
  13. // FIXME: if called directly, doesn't emit new-element event:
  14. return template;
  15. };
  16. templating.sub = function (templateId, variables) {
  17. var template = templating.clone(templateId);
  18. variables = variables || {};
  19. util.forEachAttr(variables, function (value, attr) {
  20. // FIXME: do the substitution... somehow?
  21. var subs = template.find(".togetherjs-sub-" + attr).removeClass("togetherjs-sub-" + attr);
  22. if (subs.length) {
  23. if (typeof value == "string") {
  24. subs.text(value);
  25. } else if (value instanceof $) {
  26. subs.append(value);
  27. } else {
  28. assert(false, "Unknown variable value type:", attr, "=", value);
  29. }
  30. }
  31. var ifs = template.find(".togetherjs-if-" + attr).removeClass("togetherjs-sub-" + attr);
  32. if (! value) {
  33. ifs.hide();
  34. }
  35. ifs = template.find(".togetherjs-ifnot-" + attr).removeClass("togetherjs-ifnot-" + attr);
  36. if (value) {
  37. ifs.hide();
  38. }
  39. var attrName = "data-togetherjs-subattr-" + attr;
  40. var attrs = template.find("[" + attrName + "]");
  41. attrs.each(function (index, element) {
  42. assert(typeof value == "string");
  43. element = $(element);
  44. var subAttribute = element.attr(attrName);
  45. element.attr(attrName, null);
  46. element.attr(subAttribute, value);
  47. });
  48. });
  49. if (variables.peer) {
  50. variables.peer.view.setElement(template);
  51. }
  52. if (variables.date) {
  53. var date = variables.date;
  54. if (typeof date == "number") {
  55. date = new Date(date);
  56. }
  57. var ampm = "AM";
  58. var hour = date.getHours();
  59. if (hour > 12) {
  60. hour -= 12;
  61. ampm = "PM";
  62. }
  63. var minute = date.getMinutes();
  64. var t = hour + ":";
  65. if (minute < 10) {
  66. t += "0";
  67. }
  68. t += minute;
  69. template.find(".togetherjs-time").text(t);
  70. template.find(".togetherjs-ampm").text(ampm);
  71. }
  72. // FIXME: silly this is on session:
  73. session.emit("new-element", template);
  74. return template;
  75. };
  76. return templating;
  77. });