Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Last active Dec 21, 2015
Embed
What would you like to do?
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