Lungo.View.Template.Binding.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 = lng.Constants.BINDING;
  12. var ERROR = lng.Constants.ERROR;
  13. /**
  14. * Performs databinding process for a data set and a given template
  15. *
  16. * @method process
  17. *
  18. * @param {String} Markup for binding
  19. * @param {Object} Data for binding
  20. */
  21. var process = function(markup, data) {
  22. var data_type = lng.Core.toType(data);
  23. if (data_type === 'array') {
  24. return _bindPropertiesInMultiplesElements(data, markup);
  25. } else if (data_type === 'object') {
  26. return _bindProperties(data, markup);
  27. } else {
  28. throw new Error(ERROR.BINDING_DATA_TYPE);
  29. }
  30. };
  31. var dataAttribute = function(element, attribute) {
  32. var data = element.data(attribute.tag);
  33. if (data) {
  34. var html_binded = attribute.html.replace(BINDING.START + BINDING.KEY + BINDING.END, data);
  35. element.prepend(html_binded);
  36. }
  37. };
  38. var _bindPropertiesInMultiplesElements = function(elements, template) {
  39. var markup = '';
  40. for (var i = 0, len = elements.length; i < len; i++) {
  41. markup += _bindProperties(elements[i], template);
  42. }
  43. return markup;
  44. };
  45. var _bindProperties = function(element, template) {
  46. var binding_field;
  47. for (var property in element) {
  48. if (lng.Core.isOwnProperty(element, property) && element[property] !== null) {
  49. binding_field = new RegExp(BINDING.START + property + BINDING.END, 'g');
  50. template = template.replace(binding_field, element[property]);
  51. }
  52. }
  53. return _removeNoBindedProperties(template);
  54. };
  55. var _removeNoBindedProperties = function(template) {
  56. return template.replace(BINDING.PARSER, '');
  57. };
  58. return {
  59. process: process,
  60. dataAttribute: dataAttribute
  61. };
  62. })(LUNGO);