Plugin jQuery Para Handlebars

- - falando sobre: Handlebars, Plugin, Template, jQuery

Fala manolada.

Estive usando o Handlebars e percebi que eu realizava algumas ações repetitivas, que não facilitavam em nada o desenvolvimento dos templates. Daí surgiu a idéia de criar um plugin jQuery que fizesse o simples, tendo como parâmetro o caminho do template e o do json que seria recebido para a geração do conteúdo.

jHandlebars.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
;(function ( $, window, undefined ) {
    // Nome do plugin => 'handlebars';
    var pluginName = 'handlebars',
      document = window.document,
      dataJson = null,
      templateHandleBars = null,
      defaults = {
        json: {},
        template: ''
      };

    // Construtor do nosso Plugin;
    function Plugin(element, options) {
      this.element = element;
      this.options = $.extend({}, defaults, options) ;

      this._defaults = defaults;
      this._name = pluginName;

      this.init();
    }

    Plugin.prototype = {
      //Método init();
      init: function () {
        this.refresh();
      },
      //Método refresh() que cuida de instanciar o template e o json;
      //Depois monta e compila os dados para retornar o html gerado;
      refresh: function () {
        //Verifica se o template já foi instanciado e se é uma função;
        if (!templateHandleBars && !jQuery.isFunction(templateHandleBars)) {
          templateHandleBars = this._loadTemplate();
        }
        //Verifica se já está instanciado o json de dados;
        if (!dataJson || jQuery.isEmptyObject(dataJson)) {
          dataJson = this._loadJson();
        }
        //Só é possível montar o template se o "templateHandleBars" for uma função;
        if (jQuery.isFunction(templateHandleBars)) {
          var templateHtml = templateHandleBars(dataJson);
          $(this.element).html(templateHtml);
        } else {
          $(this.element).html('Ocorreu um erro no template handleBars, verifique o caminho informado.');
        }

      },
      //Método _loadTemplate() que carrega e instancia o template handlebars;
      _loadTemplate: function () {
        var template = this._ajax(this.options.template, 'html');
        if (jQuery.type(template) === 'string') {
          return Handlebars.compile(template);
        }
        return '';
      },
      //Método _loadJson() que carrega e instancia o json de dados;
      _loadJson: function () {
        //Se o json for um objeto ele não chama o AJAX;
        if (jQuery.isPlainObject(this.options.json)) {
          return this.options.json
        } else if (jQuery.type(this.options.json) === 'string') {
          return this._ajax(this.options.json, 'json');
        }
        return {};
      },
      //Método _ajax() responsável por realizar as requisições AJAX do plugin;
      _ajax: function (url, dataType) {
        var dataReturn = null;

        $.ajax({
          url: url,
          dataType: dataType,
          async: false,
          success: function (data) {
            if (data) {
              dataReturn = data;
            }
          }
        });

        return dataReturn;
      },
    };
    //Função que instancia nosso Plugin passando o element e os options informados;
    $.fn[pluginName] = function (options) {
      return this.each(function () {
        if (!$.data(this, 'plugin_' + pluginName)) {
          $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
        }
      });
    }

  }(jQuery, window));

Para usar é muito simples

exemplo.js
1
2
3
4
5
6
7
8
9
10
11
$('#element').handlebars({
  json: {pessoas:[{nome:'italo'}, {nome:'queiroz'}]},
  template: 'caminho_do_template_handlebars.hb'
});

//ou

$('#element').handlebars({
  json: 'caminho_do_json.json',
  template: 'caminho_do_template_handlebars.hb'
});

Caso queiram colaborar fiquem a vontade, segue o link do GitHub com um exemplo do uso.

Comentários