Created
August 27, 2018 15:29
-
-
Save andresgcarmona/2d6c675a497a8ab8c4e24f9635333bc1 to your computer and use it in GitHub Desktop.
Todo Backbone View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Mustache from 'mustache'; | |
import {View} from 'backbone'; | |
import TodoItemView from 'views/todos/todo_item'; | |
import TodosCollection from 'collections/todos/todos'; | |
import TodoModel from 'models/todos/todo'; | |
import template from 'templates/todos/todos.html!text'; | |
class TodoListView extends View { | |
constructor(options) { | |
super(options); | |
this.collection = new TodosCollection(); | |
this.listenTo(this.collection, 'reset', this.addTodos); | |
this.listenTo(this.collection, 'add', this.addTodo); | |
} | |
get className() { | |
return 'todo-list'; | |
} | |
get events() { | |
return { | |
'click .load-more': 'loadMore', | |
}; | |
} | |
render() { | |
this.$el.html(Mustache.render(template)); | |
this.$list = this.$('.todos.list'); | |
this.$loadMore = this.$('.load-more'); | |
return this; | |
} | |
load(callback) { | |
let view = this; | |
this.showLoading(); | |
this.collection.fetch({ | |
data: { | |
page: this.collection.page, | |
num: this.collection.numResults, | |
}, | |
success: function() { | |
view.showLoading(false); | |
} | |
}); | |
if(callback) { | |
callback(this.collection); | |
} | |
} | |
showLoading(show = true) { | |
if(show) { | |
this.$list.append('<li class="loading list-group-item text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></li>'); | |
} | |
else { | |
this.$list.find('.loading').remove(); | |
} | |
} | |
addTodos() { | |
this.$el.empty(); | |
this.collection.each(this.addTodo, this); | |
} | |
addTodo(todo) { | |
let todoView = new TodoItemView({model: todo}); | |
todoView.on('todo:selected', this.todoSelected, this); | |
this.$list.append(todoView.render().el); | |
} | |
createTodo(val) { | |
let todo = new TodoModel({title: val}); | |
// Save todo in database. | |
todo.save(null, { | |
success: function(todo) { | |
} | |
}); | |
this.addTodo(todo); | |
} | |
loadMore() { | |
this.$loadMore.prop('disabled', true); | |
this.collection.page += 1; | |
this.load(() => { | |
this.$loadMore.prop('disabled', false); | |
}); | |
} | |
todoSelected(todo) { | |
this.trigger('todo:selected', todo); | |
} | |
} | |
export default TodoListView; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment