Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Last active December 21, 2015 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nhunzaker/d173a122b55a9486113c to your computer and use it in GitHub Desktop.
Save nhunzaker/d173a122b55a9486113c to your computer and use it in GitHub Desktop.
Refactoring to Backbone Final Result
<li class="news_item">
<h3 class="news_item_title">{{ title }}</h3>
<p class="news_item_meta">{{prettyDate date }}</p>
<p class="news_item_summary">{{ summary }}</p>
</li>
Handlebars.registerHelper('prettyDate', function(dateString) {
var date = new Date(dateString);
return [ date.getMonth(), date.getDate(), date.getFullYear() ].join("/")
});
var NewsCollection = Backbone.Collection.extend({
model: NewsModel,
url: '/my/api/news'
});
{{#each items}}
{{> _news_item}}
{{/each}}
var NewsModel = Backbone.Model.extend({
urlRoot: '/my/api/news'
});
//= require templates/_news_item
//= require templates/news_list
var NewsView = Backbone.View.extend({
tagName: 'ul',
className: 'news_widget',
template: HandlebarsTemplates['news_list'],
itemTemplate: HandlebarsTemplates['_news_item'],
initialize: function(options) {
this.listenTo(this.collection, {
'reset' : this.render,
'add' : this.addEntry
});
},
render: function() {
var markup = this.template({ items: this.collection.toJSON() });
this.$el.html(markup);
},
addEntry: function(model) {
var markup = this.itemTemplate(model.toJSON());
this.$el.append(markup);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment