Pregunta

Mi aplicación Backbone.js con Handelbars hace lo siguiente.

  1. Configurar un modelo, su colección, vista y enrutador.
  2. Al comienzo, obtenga una lista de artículos del servidor y renderice utilizando la vista a través de la plantilla Hanyebars.js.

El código está a continuación.

    (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);

La plantilla de manebars.js es

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

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

  1. Al pasar el contexto a la plantilla de manebars.js, actualmente estoy haciendo $(this.el).html(template(js[0])). ¿Es este el camino correcto? Cuando hago solo "JS" en lugar de JS [0], el objeto JSON tiene soportes cuadrados líderes y terminados. Por lo tanto, reconoce como un objeto de matriz del objeto JSON. Entonces tuve que js [0]. Pero siento que no es una solución adecuada.

  2. Cuando creo por primera vez la "vista", lo estoy creando como a continuación.

    ws._index = new ArticLelistView ({modelo: ws._articles});

Pero en mi caso, 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 parecía hacer mucha diferencia.

Gracias por adelantado.

¿Fue útil?

Solución

Parece que estás creando una vista para una colección para que debería Inicializa tu vista usando collection en vez de model.

En cuanto al manillar, no lo he usado mucho, pero creo que quieres 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 usa algo como esto para la plantilla

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

PD la líneaJSON.parse(JSON.stringify(this.model.toJSON())) es equivalente a this.model.toJSON()

Espero que esto ayude

Otros consejos

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});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top