My backbone.js app with Handelbars does the following.
- configure the model, its collection, view and router.
- at the beginning, get the list of articles from the server and render it using the view through the Handlebars.js template.
The code is below.
(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 template
<script id="articles_hb" type="text/x-handlebars-template"> {{#articles}} {{title}} {{/articles}} </script>
The code above works fine and it prints article titles. However my question is:
When passing context to the Handlebars.js template, I am currently doing $(this.el).html(template(js[0])) . Is it correct? When I do "js" instead of js [0], the JSON object has leading and trailing square brackets. Therefore, it recognizes the array object of the JSON object. So I had js [0]. But I feel that this is not the right decision.
When I first create a "View", I create it, as shown below.
ws._index = new ArticleListView ({model: ws._articles});
But in my case I had to do
ws._index = new ArticleListView({collection: ws._articles});
Is not it? (I followed the textbook). Or does it matter? I tried both, and that didn't seem to make much difference.
Thanks in advance.
ericbae
source share