Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Renamed views/todos.js to views/todo.js

  • Loading branch information...
commit b20e051a372fc3cd29644066d94c6491ccff9af1 1 parent c9dfd5e
@stuartmemo stuartmemo authored
Showing with 82 additions and 0 deletions.
  1. +82 −0 practicals/modular-todo-app/js/views/todo.js
View
82 practicals/modular-todo-app/js/views/todo.js
@@ -0,0 +1,82 @@
+define([
+ 'jquery',
+ 'underscore',
+ 'backbone',
+ 'text!templates/todos.html'
+ ], function($, _, Backbone, todosTemplate){
+ var TodoView = Backbone.View.extend({
+
+ //... is a list tag.
+ tagName: "li",
+
+ // Cache the template function for a single item.
+ template: _.template(todosTemplate),
+
+ // The DOM events specific to an item.
+ events: {
+ "click .check" : "toggleDone",
+ "dblclick div.todo-content" : "edit",
+ "click span.todo-destroy" : "clear",
+ "keypress .todo-input" : "updateOnEnter"
+ },
+
+ // The TodoView listens for changes to its model, re-rendering. Since there's
+ // a one-to-one correspondence between a **Todo** and a **TodoView** in this
+ // app, we set a direct reference on the model for convenience.
+ initialize: function() {
+ this.model.bind('change', this.render, this);
+ this.model.view = this;
+ },
+
+ // Re-render the contents of the todo item.
+ render: function() {
+ $(this.el).html(this.template(this.model.toJSON()));
+ this.setContent();
+ return this;
+ },
+
+ // To avoid XSS (not that it would be harmful in this particular app),
+ // we use `jQuery.text` to set the contents of the todo item.
+ setContent: function() {
+ var content = this.model.get('content');
+ this.$('.todo-content').text(content);
+ this.input = this.$('.todo-input');
+ this.input.bind('blur', this.close, this);
+ this.input.val(content);
+ },
+
+ // Toggle the `"done"` state of the model.
+ toggleDone: function() {
+ this.model.toggle();
+ },
+
+ // Switch this view into `"editing"` mode, displaying the input field.
+ edit: function() {
+ $(this.el).addClass("editing");
+ this.input.focus();
+ },
+
+ // Close the `"editing"` mode, saving changes to the todo.
+ close: function() {
+ this.model.save({content: this.input.val()});
+ $(this.el).removeClass("editing");
+ },
+
+ // If you hit `enter`, we're through editing the item.
+ updateOnEnter: function(e) {
+ if (e.keyCode == 13) this.close();
+ },
+
+ // Remove this view from the DOM.
+ remove: function() {
+ $(this.el).remove();
+ },
+
+ // Remove the item, destroy the model.
+ clear: function() {
+ this.model.clear();
+ }
+
+ });
+ return TodoView;
+});

0 comments on commit b20e051

Please sign in to comment.
Something went wrong with that request. Please try again.