0
votes

I have problem with render of collection. Its simple model with title and boolean 'completed', when you click on list item it's changing to completed value (true/false). Value is changed ( I know it because when I refresh page, in initialize after fetch() I have collection.pluck, where order made by comparator is correct), but view looks all the time the same.

In collection I have comparator which works like I described upper, after collection.fetch() I have pluck, and pluck gives me well sorted list (but in view I see bad, default order). I dont know how to refresh collection to be well sorted.

Collection is just:

var TodolistCollection = Backbone.Collection.extend({
    model: TodoModel,

  localStorage: new Store('todos-backbone'),


  // Sort todos
  comparator: function(todo) {
    return todo.get('completed');
  }
});

Model is:

    var TodoModel = Backbone.Model.extend({
      defaults: {
        title: '',
        completed: false
      },

      // Toggle completed state of todo item
      toggle: function(){
        this.save({
          completed: !this.get('completed')
        });
      }

    });

    return TodoModel;

Single todoView is:

var TodoView = Backbone.View.extend({
        tagName: 'li',

        template: JST['app/scripts/templates/todoView.ejs'],

        events: {
            'click .js-complete': 'toggleCompleted'
        },

        initialize: function(){
            this.listenTo(this.model, 'change', this.render);
        },

        render: function() {
            this.$el.html( this.template( this.model.toJSON() ));
            this.$el.toggleClass( 'l-completed', this.model.get('completed') );
            return this;
        },

        // Toggle the `"completed"` state of the model.
        toggleCompleted: function() {
            this.model.toggle();
        }

and app View:

var ApplicationView = Backbone.View.extend({

        el: $('.container'),

        template: JST['app/scripts/templates/application.ejs'],

        events: {
          'click #add'        : 'createOnEnter',
          'keypress #addTodo' : 'createOnEnter'
        },

        // aliasy do DOMu,
        // nasluchiwanie w kolekcji czy zaszlo jakies zdarzenie, jesli tak, to wykonuje funkcje
        initialize: function() {
          this.$input = this.$('.js-input');

          this.listenTo(todoList, 'add', this.addOne);
          this.listenTo(todoList, 'reset', this.addAll);
          this.listenTo(todoList, 'all', this.render);

          todoList.fetch();

          console.log(todoList.pluck('title'));
        },

        render: function() {

        },

        // Generate the attributes for a new Todo item.
        newAttributes: function() {
          return {
            title: this.$input.val().trim(),
            completed: false
          };
        },

        // Tworzy nowy model dzieki newAtributes() do localStorage
        addTodo: function ( e ) {
          e.preventDefault();
          if( e.which !== Common.ENTER_KEY || !this.$input.val().trim() ){
            return;
          }

          todoList.create( this.newAttributes() );

          this.$input.val('');
        },

        // Tworzy model i dopisuje go do listy
        addOne: function( todo ){
          var view = new todoView({ model: todo });
          $('.js-todolist').append( view.render().el );
        },

        // Tworzy nowego todo gdy nacisniemy enter
        createOnEnter: function( e ) {
          if( e.which !== Common.ENTER_KEY || !this.$input.val().trim() ){
            return;
          }

          todoList.create( this.newAttributes() );
          this.$input.val('');
        },

        // Przy rerenderze, dodaj wszystkie pozycje
        addAll: function() {
          this.$('.js-todolist').html('');
          todoList.each(this.addOne, this);
        }

    });

    return ApplicationView;

When I change listenTo render like that: this.listenTo(todoList, 'all', function(){console.log('whateva')}); I can see that on my click 'all' is triggering (even three times per one click ;s ).

Its hard for me to put it on jsfiddle, but here's git link with all files: https://github.com/ozeczek/ozeczek/tree/master/bb-todo-yo/app/scripts

1
Have You tried Backbone Marionette? It automates this logic described here.VuesomeDev
First I want to understand how the framework is working, then I will play with marionette :)norbert
tried calling sort on the collection?VuesomeDev
could you tell me what do you mean exacly ?norbert
Nothing changes, still this.listenTo(todoList, 'all', function(){ this.comparator; this.render; console.log(todoList.pluck('title')); }); is in the same, unchanged ordernorbert

1 Answers

1
votes

In app view initialize I've changed todoList.fetch() to todoList.fetch({reset:true});

Second problem was to show in browser right order of todos, I've added to initialize:

this.listenTo(todoList, 'change', this.walcze);
this.listenTo(todoList, 'remove', this.walcze);

and walcze body function is:

walcze: function(){

          todoList.sort();

          this.$('.js-todolist').html('');
          todoList.each(this.addOne, this);
        }

Now every time Todo paremeter complete is changed, Im sorting list (comparator by itself isn't), clearing div with list, and rewriting whole list. I think it is not the best way of doing it, but it works.