0
votes

In my backbone project, my model is not updated after the 'add' method that I call in a Collection. I don't understand why.

I'm sure I'm doing something badly but I cannot figure what.

https://github.com/blured75/CardScores/blob/master/public/js/tweets.js

On the initialize function of my view, I call bind 'add' to this.render (of the view)

initialize: function() {
            this.model.on('add', this.render, this);
},

In the render function of my view, this.model has no specific attributes, only {length: 1, models: Array(1), _byId: {…}, _events: {…}}

render: function() {
    console.log('in render this.model', this.model);
    ...
}

The function used for the submit event of #new-tweet is well called and the tweet object is well populated :

The method $('#new-tweet').submit(function(ev) {
            var tweet = new Tweet({ author: $('#author-name').val(), status: $('#status-update').val()});   
            console.log('adding : ', tweet.toJSON());
            tweets.add(tweet);

            return false;
        });

Do you see something erroneous apart the fact of using an old framework ?

1

1 Answers

1
votes

[Description]
The problem is, the first argument of _.each has to be "list". (https://underscorejs.org/#each)

As your console.log(this.model) in TweetsView, although it is a backbone collection...

It is an Object.

{
    length: 1, 
    models: Array(1), 
    _byId: {…}, 
    _events: {…}
}

so the each cannot work normally.

[Improvement]
I provide two ways:

  1. Use the each function of Backbone.Collection.
this.model.each(function(tweet, i) {
    console.log(i);
    console.log(tweet); // Undefined ???
    console.log((new TweetView({model: tweet})).render().$el);
    self.$el.append((new TweetView({model: tweet})).render().$el);
});
  1. Because the this.model.models is Array, visit it directly.
_.each(this.model.models, function(tweet, i) {
    console.log(i);
    console.log(tweet); // Undefined ???
    console.log((new TweetView({model: tweet})).render().$el);
    self.$el.append((new TweetView({model: tweet})).render().$el);
});