I’m playing around with Backbone.js for the first time, and I’m having a bit of trouble.
My initial intention was to show the content of a certain slide, but I’ve fallen back to ‘just trying to display anything’ with the .text() method.
My render method get’s called, I can see that in the log, but the ‘currentslide’ id is not filled. Does anyone know what silly thing I’m overlooking here?
Seeing as the Backbone code seems to do ok, it might be a jQuery related issue. I’m pretty new to both of them.
Many thanks in advance,
Dieter
This is my html:
<!doctype html>
<head>
<meta charset="utf-8">
<title>Presentation</title>
<script src="js/vendor/jquery-1.5.1.min.js"></script>
<script src="js/vendor/underscore.js"></script>
<script src="js/vendor/backbone.js"></script>
<script src="js/slides.js"></script>
</head>
<body>
<div id="container">
<div id="slideshow">
<h2 id="currentslide"></h2>
</div>
</div>
</body>
And this is my Backbone code so far:
(function($) {
window.Slide = Backbone.Model.extend({
content: "Testcontent",
initialize: function() {
console.log('Slide created');
}
});
window.Slidedeck = Backbone.Collection.extend({
model: Slide,
});
window.Slideshow = Backbone.View.extend({
el: $('#slideshow'),
currentSlide: 0,
initialize: function() {
_.bindAll(this, 'render');
},
render: function (){
console.log('Rendering');
$('#currentslide').text('This aint even working darned.');
return this;
}
});
var slidedeck = new Slidedeck([
new Slide({
content: "Slide 1",
}),
new Slide({
content: "Slide 2",
}),
]);
var slideshow = new Slideshow({
collection: slidedeck,
});
slideshow.render();
})(jQuery);
EDIT:
I tried the suggestion to replace the last line of code with
$(slideshow.render().el).appendTo('body');
But that doesn’t seem to work unfortunately.
The weird thing is that I have another piece of code with a render() where the .text() works perfectly.
render: function (){
$('#actionValue').text(this.model.get('value'));
return this;
}
Since the render() code gets run on both pieces of code, I assume it has nothing to do with binding anything.
But for some reason the latter does its .text() just fine, the first one does not.
In your case, the element
#slideshowalready exists in your HTML, so you don’t need to append it to the body as specified in @czarchaic’s answer.You’re having issues because you’re attempting to render and set the value of
#slideshowbefore it exists in the DOM. This happens because you’ve includedjs/slides.jsbefore the DOM elements are created. The JS is included and executed, but whenslideshow.render()is called, the#slideshowelement has not yet been created, so$('#slideshow')will return no elements, thustext()is doing nothing.You need to either…
Move your JavaScript include to after the DOM elements creation
Or you need to wrap your
rendercall in a document ready block