Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-events

Why backbone.js doesn't render the view in this example?


I am started learning backbone.js and working a sample backbone application, where tweets feeds of search term is populated in view of backbone from tweeter API.

The following is my code for backbone MVC.

BackboneSample.js

$(function() {
    var Tweet = Backbone.Model.extend();

    var Tweets = Backbone.Collection.extend({
        model: Tweet,
        url: 'http://search.twitter.com/search.json?q=NYC&callback=?',
        parse: function(response) {
            console.log('parsing ...');
            console.log('parsing ...');
            return response.results;
        }
    });
    var PageView = Backbone.View.extend({
        el: $('body'),
        events: {
            'click button#add': 'doSearch'
        },
        initialize: function() {
            _.bindAll(this);
            this.tweets = new Tweets();
            _this = this;
            this.tweets.on('reset', function(collection) {
                _this.$('#tweets').empty();
                collection.each(function(tweet) {
                    _this.addItem(tweet);
                });
            });
            this.counter = 0;
            this.render();
        },
        doSearch: function() {
            var subject = $('#search').val() || 'NYC';
            this.tweets.url = 'http://search.twitter.com/search.json?q=' + subject + '&callback=?';
            this.tweets.fetch();
        },
        render: function() {
            $(this.el).append("<input id= 'search'type='text' placeholder='Write a word' />");
            $(this.el).append("<button id='add'>Search twitts</button>");
            $(this.el).append("<ul id='tweets'></ul>");
            return this;
        },
        addItem: function(item) {
            console.log(item);
            $('ul', this.el).append("<li><b>" + item.get('from_user_name') + "</b>:  " + item.get('text') + "</li>");

        }
    });
    var pageView = new PageView();
});

But this doesn't work as I expected. The tweets are not coming in view after rendering page. The JSON response data is returning from tweeter API, but the view is not reflecting the change. What will be error happened here? How I can solve this problem?

Please check the demo in fiddle.


Solution

  • Since the 1.0 version of Backbone fetch don't trigger the reset event automatically, but will use instead collection.set to merge the fetched model with the others you already have. To effectively reset your collection you should change your fetch call like this:

    this.tweets.fetch({reset:true});
    

    More info in the official docs.