Reputation: 4197
I am new to backbone and am doing a project to teach myself. For some reason I cannot get the events hash to work so I did a good amount of things in the initialize function instead. How would I use the events hash in my view below?
var PictureView = Backbone.View.extend({
el: "#app",
initialize: function() {
$('.button').click(function() {
this.request();
}.bind(this))
},
request: function(text) {
var text = $('#text').val();
this.getPicture(text, function(url) {
console.log(arguments)
//append it to the image tag;
$("#random").attr("src", url)
});
},
getPicture: function(tags, cb) {
$.getJSON(
"https://api.flickr.com/services/rest/?jsoncallback=?", {
method: 'flickr.photos.search',
tags: tags,
api_key: apiKey,
format: 'json',
nojsoncallback: 1,
per_page: 10 // you can increase this to get a bigger array
},
function(data) {
if (data.stat === 'ok') {
var photo = data.photos.photo[Math.floor(Math.random() * data.photos.photo.length)];
$.getJSON(
"https://api.flickr.com/services/rest/?jsoncallback=?", {
method: 'flickr.photos.getSizes',
api_key: apiKey,
photo_id: photo.id,
format: 'json',
nojsoncallback: 1
},
function(response) {
console.log(response);
if (response.stat === 'ok') {
var the_url = response.sizes.size[5].source;
cb(the_url);
} else {
console.log(" The request to get the picture was not good :\ ")
}
}
);
} else {
alert("no pictures found for that tag :'(");
}
}
);
}
})
Upvotes: 0
Views: 53
Reputation: 932
Your button is outside the div with id #app
. In Backbone, for the events hash to work, the elements you want to use the events on, should be inside your el.
<center><div id="app">
<center><button class="button">Click Me to add an image</button</center>
</div></center>
Now you can use the events hash as
el: "#app",
events: { 'click .button': 'request' },
initialize : function(){}
Upvotes: 3