Lungo.View.Template.Binding.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * Lungo Data-Binding system
  3. *
  4. * @namespace LUNGO.View.Template
  5. * @class Binding
  6. * @requires Zepto
  7. *
  8. * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
  9. * @author Guillermo Pascual <pasku@tapquo.com> || @pasku1
  10. */
  11. LUNGO.View.Template.Binding = (function(lng, undefined) {
  12. var BINDING_START = '{{';
  13. var BINDING_END = '}}';
  14. var BINDING_PARSER = /\{{.*?\}}/gi;
  15. /**
  16. * Performs databinding process for a data set and a given template
  17. *
  18. * @method create
  19. *
  20. * @param {String} Id of the container showing the result of databinding
  21. * @param {Number} Databinding Template Id
  22. * @param {Object} Data for binding
  23. * @param {Function} Callback when the process is complete
  24. */
  25. var create = function(container_id, id, data, callback) {
  26. if (lng.View.Template.exists(id)) {
  27. var template = lng.View.Template.get(id);
  28. var markup = _processData(data, template);
  29. _render(container_id, markup);
  30. lng.Core.execute(callback);
  31. } else {
  32. lng.Core.log(3, 'lng.View.Template.binding: id ' + id + ' not exists');
  33. }
  34. };
  35. var dataAttribute = function(element, attribute) {
  36. var data = element.data(attribute.tag);
  37. if (data) {
  38. var html_binded = attribute.html.replace(BINDING_START + 'value' + BINDING_END, data);
  39. element.prepend(html_binded);
  40. }
  41. };
  42. var _processData = function(data, template) {
  43. var data_type = lng.Core.toType(data);
  44. if (data_type === 'array') {
  45. return _bindPropertiesInMultiplesElements(data, template);
  46. } else if (data_type === 'object') {
  47. return _bindProperties(data, template);
  48. } else {
  49. lng.Core.log(3, 'View.Template ERROR >> No type defined.');
  50. }
  51. };
  52. var _bindPropertiesInMultiplesElements = function(elements, template) {
  53. var markup = '';
  54. for (var i = 0, len = elements.length; i < len; i++) {
  55. markup += _bindProperties(elements[i], template);
  56. }
  57. return markup;
  58. };
  59. var _bindProperties = function(element, template) {
  60. for (var property in element) {
  61. if (lng.Core.isOwnProperty(element, property)) {
  62. template = template.replace(BINDING_START + property + BINDING_END, element[property]);
  63. }
  64. }
  65. return _removeNoBindedProperties(template);
  66. };
  67. var _removeNoBindedProperties = function(template) {
  68. return template.replace(BINDING_PARSER, '');
  69. };
  70. var _render = function(container_id, markup) {
  71. var container = lng.Dom.query('#' + container_id);
  72. container.html(markup);
  73. };
  74. return {
  75. create: create,
  76. dataAttribute: dataAttribute
  77. };
  78. })(LUNGO);