Backbone Fetch Test
Backbone Fetch Test
by Nirvanachain
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/template" id="dropdownList">
<% console.log('this is the template') %>
<% console.log(collection) %>
<div>
<h3>Stat = <%- collection.stat %></h3>
<select class="js-selectMenu">
<% _.each(tagOptions, function (element, index) { %>
<%console.log('element =', element) %>
<option value="<%- element %>"><%- element %></option>
<% }); %>
</select>
</div>
</script>
<script type="text/template" id="resultsList">
<h3>Results!!!</h3>
</script>
<div class="js-container">
</div>
JavaScript
var TheModel = Backbone.Model.extend({
default: {
photos: '',
stat: ''
}
});
var TheCollection = Backbone.Collection.extend({
model: TheModel,
url: 'http://api.flickr.com/services/rest/'
});
// The main view
var Parent = Backbone.View.extend({
el: '.js-container',
initialize: function () {
this.collection = new TheCollection();
return this;
},
render: function (tag) {
var self = this,
tagOptions = ['kitten', 'puppy', 'candy'],
urlParamTag;
//Set the value of the urlParameter passed to the ajax url.
if (tag === undefined) {
urlParamTag = 'kittens,puppies,candy';
} else {
urlParamTag = tag;
}
console.log('urlParamTag =',urlParamTag);
var urlParameters = {
page : '1',
api_key: 'a2978e5ce30c337e3b639172d3e1a0d1',
tags: urlParamTag,
tag_mode: 'all',
method: 'flickr.photos.search',
per_page: '10',
format: 'json'
};
this.collection.fetch({
dataType: 'jsonp',
jsonpCallback: 'jsonFlickrApi',
data: urlParameters,
success: function (data) {
console.log('success');
console.log(self.collection);
var template = _.template( $('#dropdownList').html(), {
collection: self.collection.toJSON()[0],
tagOptions: tagOptions
} );
self.$el.html(template);
}
});
return this;
},
events: {
'change .js-selectMenu': 'pickOne'
},
pickOne: function (event) {
var selectionValue = event.currentTarget.value;
console.log(selectionValue);
this.render(selectionValue);
return...