todoListView.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Create a view class, just like a model view.
  2. const TodoListView = Backbone.View.extend({
  3. initialize() {
  4. this.collection.on('add', this.addOne, this);
  5. },
  6. // First attempt (bad) at doing a list render.
  7. renderNaive() {
  8. this.collection.forEach(function (todoItem) {
  9. const todoView = new TodoView({ model: todoItem });
  10. // Problem, "this" is the wrong context is it is needed for rendering.
  11. this.$el.append(todoView.render().el);
  12. });
  13. },
  14. addOne: function (todoItem) {
  15. const todoView = new TodoView({ model: todoItem });
  16. const rendered = todoView.render();
  17. this.$el.append(rendered.el);
  18. },
  19. render: function () {
  20. // Now pass the proper context to the loop callback.
  21. this.collection.forEach(this.addOne.bind(this));
  22. return this;
  23. }
  24. });
  25. function todoViewListExample(list) {
  26. // Note: collection (not model) being passed.
  27. const todoListView = new TodoListView({
  28. collection: list,
  29. });
  30. todoListView.render();
  31. console.log(todoListView.el);
  32. // Apply to the DOM.
  33. $('#app').html(todoListView.el);
  34. }
  35. $(function () {
  36. globalList = todoListFromServer();
  37. todoViewListExample(globalList);
  38. });