Skip to content

Instantly share code, notes, and snippets.

@boo1ean
Created September 17, 2014 15:24
Show Gist options
  • Save boo1ean/f0868bab3df29b776240 to your computer and use it in GitHub Desktop.
Save boo1ean/f0868bab3df29b776240 to your computer and use it in GitHub Desktop.
var Task = Backbone.Model.extend({
urlRoot: '/tasks',
idAttribute: "_id",
defaults: {
status: 'new'
},
clear: function() {
this.unset('_id');
}
});
var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
var CreateTaskView = Backbone.View.extend({
template: _.template($('#create-task-template').html()),
events: {
'click .submit-button': 'submit'
},
render: function() {
this.$el.html(this.template());
},
submit: function(e) {
e.preventDefault();
var title = $('.title-input').val();
var self = this;
this.model.save({ title: title }).then(function() {
$('.title-input').val('');
self.trigger('task:created', self.model);
self.model.clear();
});
}
});
var TasksCollectionItemView = Backbone.View.extend({
itemTemplate: _.template($('#task-template').html()),
events: {
'click .btn-danger': 'destroy'
},
render: function() {
this.$el.html(this.itemTemplate(this.model.toJSON()));
return this;
},
destroy: function() {
this.model.destroy();
}
});
var TasksCollectionView = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
this.listenTo(this.collection, 'destroy', this.render);
},
render: function() {
var $el = this.$el;
$el.empty();
this.collection.models.reverse().forEach(function(model) {
var itemView = new TasksCollectionItemView({ model: model });
$el.append(itemView.render().el);
}, this);
}
});
var task = new Task();
var view = new CreateTaskView({
el: '#main',
model: task
});
var collection = new Tasks();
var collectionView = new TasksCollectionView({
el: '#collection',
collection: collection
});
collection.fetch();
view.render();
view.on('task:created', function(model) {
collection.add(model.toJSON());
collectionView.render();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment