我是backbonejs和underscorejs的新手。我发现了一些video材料,我试图修改示例时遇到问题。
这是我的代码:
<html>
<head >
<meta charset="UTF-8">
<script type="text/javascript" src="javascript/jQuery.js"></script>
<script type="text/javascript" src="javascript/underscore.js"></script>
<script type="text/javascript" src="javascript/backbone.js"></script>
<script type="text/template" id="list-template">
<li><a href="<%= href %>"><%= text %></a></li>
</script>
<script type="text/javascript">
model = new Backbone.Model({
data: [
{text: "Google", href: "google.com"},
{text: "Facebook", href: "facebook.com"},
{text: "Yahoo", href: "yahoo.com"}
]
});
var View = Backbone.View.extend({
el: "#container",
events: {
"click button": "render"
},
render: function(){
var data = this.model.get('data');
for(var i = 0; i<data.length; i++){
var variables = { href: data[i].href, text: data[i].text };
var li = _.template( $("#list-template").html(), variables );
this.$el.find('ul').append(li);
}
}
});
var view = new View({ model: model });
</script>
</head>
<body>
<div id="container">
<button>Load</button>
<ul id="list">
</ul>
</div>
</body>
它当然不起作用,我找不到原因。如果您看到请回答或指导如何在自定义事件上绑定模板,而不是初始化。
答案 0 :(得分:5)
问题是JavaScript在页面上呈现元素之前正在执行。将代码包裹在$(document).ready()
:
$(document).ready(function() {
var model = new Backbone.Model({
....
var view = new View({ model: model });
});