Lungo.View.Template.Binding.js 2.3 KB

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