12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- // Create a view class, just like a model view.
- const TodoListView = Backbone.View.extend({
- initialize() {
- this.collection.on('add', this.addOne, this);
- this.collection.on('reset', this.addAll, this);
- },
- // First attempt (bad) at doing a list render.
- renderNaive() {
- this.collection.forEach(function (todoItem) {
- const todoView = new TodoView({ model: todoItem });
- // Problem, "this" is the wrong context is it is needed for rendering.
- this.$el.append(todoView.render().el);
- });
- },
- addAll: function (todoItems) {
- this.collection.forEach(this.addOne.bind(this));
- return this;
- },
- addOne: function (todoItem) {
- const todoView = new TodoView({ model: todoItem });
- const rendered = todoView.render();
- this.$el.append(rendered.el);
- },
- render: function () {
- // Now pass the proper context to the loop callback.
- // this.collection.forEach(this.addOne.bind(this));
- // Or use our new addAll()
- return this.addAll();
- }
- });
- function todoViewListExample(list) {
- // Note: collection (not model) being passed.
- const todoListView = new TodoListView({
- collection: list,
- });
- todoListView.render();
- console.log(todoListView.el);
- // Apply to the DOM.
- $('#app').html(todoListView.el);
- return todoListView;
- }
- $(function () {
- globalList = todoListFromServer();
- globalListView = todoViewListExample(globalList);
- });
|