Backbone - listenTo() - Working?

Backbone - listenTo() - Working?

by Nirvanachain

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script type="text/template" id="List">
    <button class="js-button">Click for the next page</button>
    <% console.log('templates collection=',collection) %>
    <ul>
        <% _.each(collection, function (element, index) { %>
            <% _.each(element.photos.photo, function(ele, i) { %>
               <li>
                   <img src="http://farm<%- ele.farm %>.staticflickr.com/<%- ele.server %>/<%- ele.id %>_<%- ele.secret %>_m.jpg" />
               </li>
            <% }); %>
        <% }); %>
    </ul>       
</script>


<div class="js-container">
    
</div>

CSS

ul > * {
    display: inline-block;
    vertical-align: top;
    width: 25%;
}

img {
    width: 100%;
}

JavaScript

var urlParameters = {
    page: 1,
    api_key:'a2978e5ce30c337e3b639172d3e1a0d1',
    tags: 'cats',
    method: 'flickr.photos.search',
    per_page: 3,
    format: 'json'
};

var TheModel = Backbone.Model.extend({
    default: {
        photos: '',
        stat: ''   
    }
});

var TheCollection = Backbone.Collection.extend({
    model: TheModel,

    url: 'http://api.flickr.com/services/rest'

});

var TheView = Backbone.View.extend({
    el: '.js-container',
    
    initialize: function () {
        this.collection = new TheCollection();

        this.fetchData();

        this.listenTo(this.collection, 'reset', this.render);
        
        return this;
    }, 
    
    render: function () {        
        var temp = _.template( $('#List').html(), {collection: this.collection.toJSON()} );      
        this.$el.html(temp);   
        
        return this;
    },
    
    fetchData: function () {
        var self = this;
        this.collection.fetch({
            reset: 'true',
            type: 'GET',
            dataType:'jsonp',
            data: urlParameters,
            jsonp:'jsoncallback',
            success: function (data) {
               console.log('self.collection =',self.collection); 
            },
            error: function () {
                console.log('ERROR!!!');
            }
        });    
        
        return this;
    },
    
    events: {
        'click .js-button': 'nextPage'   
    },
    
    nextPage: function () {
        urlParameters.page = urlParameters.page + 1;
        this.fetchData();
        
        return this;
    }
    
});

var theView = new TheView();
return theView;