Backbone - listenTo()
Backbone - listenTo()
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) %>
<% _.each(collection, function (element, index) { %>
<% _.each(element.photos.photo, function(ele, i) { %>
<img src="http://farm<%- ele.farm %>.staticflickr.com/<%- ele.server %>/<%- ele.id %>_<%- ele.secret %>_m.jpg" />
<% }); %>
<% }); %>
</script>
<div class="js-container">
</div>
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, 'change', 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({
type: 'GET',
dataType:'jsonp',
data: urlParameters,
jsonp:'jsoncallback',
success: function (data) {
console.log('self.collection =',self.collection.toJSON());
},
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();
theView.render();