Lungo.View.Template.Binding.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 create
  17. *
  18. * @param {String} Databinding Template Id
  19. * @param {Object} Data for binding
  20. */
  21. var create = function(template_id, data) {
  22. var template = lng.View.Template.get(template_id);
  23. return _processData(data, template);
  24. };
  25. var dataAttribute = function(element, attribute) {
  26. var data = element.data(attribute.tag);
  27. if (data) {
  28. var html_binded = attribute.html.replace(BINDING.START + BINDING.KEY + BINDING.END, data);
  29. element.prepend(html_binded);
  30. }
  31. };
  32. var _processData = function(data, template) {
  33. var data_type = lng.Core.toType(data);
  34. if (data_type === 'array') {
  35. return _bindPropertiesInMultiplesElements(data, template);
  36. } else if (data_type === 'object') {
  37. return _bindProperties(data, template);
  38. } else {
  39. lng.Core.log(3, ERROR.BINDING_DATA_TYPE);
  40. }
  41. };
  42. var _bindPropertiesInMultiplesElements = function(elements, template) {
  43. var markup = '';
  44. for (var i = 0, len = elements.length; i < len; i++) {
  45. markup += _bindProperties(elements[i], template);
  46. }
  47. return markup;
  48. };
  49. var _bindProperties = function(element, template) {
  50. var binding_field;
  51. for (var property in element) {
  52. if (lng.Core.isOwnProperty(element, property) && element[property] !== null) {
  53. binding_field = new RegExp(BINDING.START + property + BINDING.END, 'g');
  54. template = template.replace(binding_field, element[property]);
  55. }
  56. }
  57. return _removeNoBindedProperties(template);
  58. };
  59. var _removeNoBindedProperties = function(template) {
  60. return template.replace(BINDING.PARSER, '');
  61. };
  62. return {
  63. create: create,
  64. dataAttribute: dataAttribute
  65. };
  66. })(LUNGO);