BB: Collection data handling
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css">
<div class="js-app"></div>
<script type="text/template" class="tmpl-order">
{{name}}
</script>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
Babel + JSX
console.clear();
// Reading https://github.com/jashkenas/backbone/issues/3560
// https://github.com/epicmiller/es2015-default-class-properties
// http://benmccormick.org/2015/07/06/backbone-and-es6-classes-revisited/
/**
* @todos
* - Render out a collection
* - Trigger a payload that gets picked up by collection
* - Add a model and just set it
* -
*/
var data = [
{
"name": "Order 1",
"type": 1
}, {
"name": "Order 2",
"type": 1
}, {
"name": "Order 3",
"type": 2
}
];
const OrderModel = Backbone.Model.extend({
parse(response) {
console.log(response)
var model = _.clone(response);
model.name = `+${response.name}`;
return model;
}
});
const OrdersCollection = Backbone.Collection.extend({
model: OrderModel,
initialize() {
setTimeout(() => {
this.trigger('snapshot', data);
}, 1000);
setTimeout(() => {
this.trigger('snapshot', data);
}, 2000);
this.listenTo(this, 'snapshot', this.setCollection, this);
},
setCollection(response) {
this.reset(response, {parse: true});
}
});
const OrdersView = Backbone.View.extend({
tagName: 'ul',
initialize() {
this.listenTo(this.collection, 'reset', this.renderRows, this);
},
render() {
this.$el.html();
return this;
},
renderRows() {
this.$el.empty()
this.collection.each(this.renderRow, this);
},
renderRow(model) {
var orderRow = new OrderView({
model: model
});
this.$el.append(orderRow.render().el);
return this;
}
});
const OrderView = Backbone.View.extend({
tagName: 'li',
template: Handlebars.compile($('.tmpl-order').html()),
render() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
const ordersView = new OrdersView({
collection: new...