PageRenderTime 40ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/labs/architecture-examples/backbone.xmpp/js/views/todos.js

https://github.com/1manStartup/todomvc
JavaScript | 88 lines | 55 code | 18 blank | 15 comment | 5 complexity | 96c67efbc18f2a9032ea736fb5315388 MD5 | raw file
  1. var app = app || {};
  2. $(function() {
  3. 'use strict';
  4. // Todo Item View
  5. // --------------
  6. // The DOM element for a todo item...
  7. app.TodoView = Backbone.View.extend({
  8. //... is a list tag.
  9. tagName: 'li',
  10. // Cache the template function for a single item.
  11. template: _.template( $('#item-template').html() ),
  12. // The DOM events specific to an item.
  13. events: {
  14. 'click .toggle': 'togglecompleted',
  15. 'dblclick label': 'edit',
  16. 'click .destroy': 'clear',
  17. 'keypress .edit': 'updateOnEnter',
  18. 'blur .edit': 'close'
  19. },
  20. // The TodoView listens for changes to its model, re-rendering. Since there's
  21. // a one-to-one correspondence between a **Todo** and a **TodoView** in this
  22. // app, we set a direct reference on the model for convenience.
  23. initialize: function() {
  24. this.model.on( 'change', this.render, this );
  25. this.model.on( 'destroy', this.remove, this );
  26. this.model.collection.on( 'remove', this.remoteRemove, this);
  27. },
  28. remoteRemove: function (model) {
  29. if (model.id === this.model.id) {
  30. this.remove();
  31. }
  32. },
  33. // Re-render the titles of the todo item.
  34. render: function() {
  35. this.$el.html( this.template( this.model.toJSON() ) );
  36. this.$el.toggleClass( 'completed', this.model.get('completed') );
  37. this.input = this.$('.edit');
  38. return this;
  39. },
  40. // Toggle the `"completed"` state of the model.
  41. togglecompleted: function() {
  42. this.model.toggle();
  43. },
  44. // Switch this view into `"editing"` mode, displaying the input field.
  45. edit: function() {
  46. this.$el.addClass('editing');
  47. this.input.focus();
  48. },
  49. // Close the `"editing"` mode, saving changes to the todo.
  50. close: function() {
  51. var value = this.input.val().trim();
  52. if ( value ) {
  53. this.model.save({ title: value });
  54. } else {
  55. this.clear();
  56. }
  57. this.$el.removeClass('editing');
  58. },
  59. // If you hit `enter`, we're through editing the item.
  60. updateOnEnter: function( e ) {
  61. if ( e.which === ENTER_KEY ) {
  62. this.close();
  63. }
  64. },
  65. // Remove the item, destroy the model from *localStorage* and delete its view.
  66. clear: function() {
  67. this.model.destroy();
  68. }
  69. });
  70. });