2011-09-08 14 views
7

Mi aplicación backbone.js con Handelbars hace lo siguiente.Preguntas sobre Backbone.js con Handlebars.js

  1. configure un modelo, su colección, vista y enrutador.
  2. al comienzo, obtenga una lista de artículos del servidor y renderícelos usando la vista a través de la plantilla Handlebars.js.

El código está debajo.

plantilla
(function ($) 
    { 
     // model for each article 
     var Article = Backbone.Model.extend({}); 

     // collection for articles 
     var ArticleCollection = Backbone.Collection.extend({ 
     model: Article 
     }); 

     // view for listing articles 
     var ArticleListView = Backbone.View.extend({ 
     el: $('#main'), 
     render: function(){ 
      var js = JSON.parse(JSON.stringify(this.model.toJSON())); 
      var template = Handlebars.compile($("#articles_hb").html()); 
      $(this.el).html(template(js[0])); 
      return this; 
     } 
     }); 

     // main app 
     var ArticleApp = Backbone.Router.extend({ 
     _index: null, 
     _articles: null, 

     // setup routes 
     routes: { 
      "" : "index" 
     }, 

     index: function() { 
      this._index.render(); 
     }, 

     initialize: function() { 
      var ws = this; 
      if(this._index == null) { 
      $.get('blogs/articles', function(data) { 
       var rep_data = JSON.parse(data); 
       ws._articles = new ArticleCollection(rep_data); 
       ws._index = new ArticleListView({model: ws._articles}); 
       Backbone.history.loadUrl(); 
      });    
      return this; 
     } 
     return this; 
     } 
    }); 

    articleApp = new ArticleApp(); 
    })(jQuery); 

Handlebars.js es

<script id="articles_hb" type="text/x-handlebars-template"> 
    {{#articles}} 
    {{title}} 
    {{/articles}} 
</script> 

El código anterior funciona bien y se imprime títulos de los artículos. Sin embargo, mi pregunta es

  1. Al pasar a la plantilla de contexto Handlebars.js, actualmente estoy haciendo $(this.el).html(template(js[0])). ¿Es este el camino correcto? Cuando hago simplemente "js" en lugar de js [0], el objeto JSON tiene corchetes iniciales y finales. Por lo tanto, reconoce como un objeto de matriz de objeto JSON. Entonces tuve que js [0]. Pero siento que no es una solución adecuada.

  2. Cuando primero creo la "Vista", la estoy creando como a continuación.

    ws._index = new ArticleListView ({model: ws._articles});

Pero en mi caso, yo debería hacer

ws._index = new ArticleListView({collection: ws._articles}); 

no debería? (Estaba siguiendo un tutorial por cierto). ¿O esto importa? Intenté ambos, y no pareció hacer mucha diferencia.

Gracias de antemano.

+0

cómo puedo incluir este handlebar.js plantilla en mi html – Vinodh

Respuesta

24

Parece que va a crear una visión para una colección para que debe inicializar su vista usando collection en lugar de model.

En cuanto a los manillares, no he usado mucho, pero creo que quiere hacer algo como esto:

var ArticleListView = Backbone.View.extend({ 
    el: $('#main'), 
    render: function(){ 
     var js = this.collection.toJSON(); 
     var template = Handlebars.compile($("#articles_hb").html()); 
     $(this.el).html(template({articles: js})); 
     return this; 
    } 
    }); 

y luego usar algo como esto para la plantilla

{{#each articles}} 
    {{this.title}} 
    {{/each}} 

ps la línea JSON.parse(JSON.stringify(this.model.toJSON())) es equivalente a this.model.toJSON()

espero que esto ayude

+0

fresco. eso de hecho ayuda. – ericbae

2
var ArticleListView = Backbone.View.extend({ 
    initialize: function(){ 
     this.template = Handlebars.compile($('#articles_hb').html()); 
    }, 
    render: function(){ 
     $(this.el).html(this.template(this.model.toJSON())); 
     return this; 
    } 
    }); 

//////////////////////////// /////////

ws._index = new ArticleListView({model: ws._articles});