Mi aplicación backbone.js con Handelbars hace lo siguiente.Preguntas sobre Backbone.js con Handlebars.js
- configure un modelo, su colección, vista y enrutador.
- 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
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.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.
cómo puedo incluir este handlebar.js plantilla en mi html – Vinodh