I’m learning Backbone.js and got stuck on this simple example. Could you explain what’s wrong with this code, that makes the alert box show up empty?
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js" type="text/javascript"></script>
</head>
<body>
<div id="test_div">test</div>
<script>
$(function() {
TestView = Backbone.View.extend({
tagName: "div",
initialize: function() {
alert(this.$("#test_div").text());
}
});
window.App = new TestView;
});
</script>
</body>
</html>
What are you expecting? There is no text in your div, therefore it alerts empty. If you want to see text in there you’ll have to add some to
this.elfirst.Edit:
this.$is scoped tothis.elI see that you’re trying to access that. Unless you specifythis.elto be body likeThen
this.$will work. However, you can simply omit thethisand use$("#test_div").text()