Iam学习Backbone JS,为什么我的下面代码没有显示在浏览器中?我甚至使用过路由器,但仍未在浏览器中显示。请告诉我出了什么问题。顺便说一下,输出只在控制台中显示。对不起,如果它的愚蠢查询。
<html>
<head>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
<script type="text/javascript">
/*$.getJSON('api/users/1',function(data){
console.log(data);
});*/
</script>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script type="text/javascript">
var TodoItem = Backbone.Model.extend({
toggleStatus: function(){
if(this.get('status') == 'incomplete'){
this.set({'status':'complete'});
} else {
this.set({'status':'incomplete'});
}
}
})
var TodoView = Backbone.View.extend({
template: _.template('<h3> ' +'<input type=checkbox ' +'<% if(status === "complete") print("checked") %>/>' +' <%= description %></h3>'),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
},
events: {
'change imput': 'toggleStatus'
},
toggleStatus : function(){
this.model.toggleStatus();
}
})
var todoItem = new TodoItem({ description: 'Pick up milk', status: 'incomplete', id: 1 });
var todoView = new TodoView({model: todoItem});
console.log(todoView.el);
var Router = Backbone.Router.extend({
routes: {
'': 'home'
}
});
var router = new Router();
router.on('route:home' , function(){
todoView.render();
});
Backbone.history.start();
</script>
</body>
</html>
答案 0 :(得分:1)
每个视图都应该以这种方式呈现,当你想创建新元素时,指定tagName,className和id,当需要一个元素来向它追加视图时你应该指定el来选择它(jquery选择它)。您的代码的下一期是您不在渲染函数中返回此代码。当你有嵌套视图时,你应该返回它。
我在这个垃圾箱里测试了它 http://jsbin.com/jefuyuxanu/2/edit
答案 1 :(得分:0)
您的TodoView未附加到DOM中。
为您的视图设置“el”属性
var TodoView = Backbone.View.extend({
el:'body',
template: _.template('<h3> ' +'<input type=checkbox ' +'<% if(status === "complete") print("checked") %>/>' +' <%= description %></h3>'),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events: {
'change imput': 'toggleStatus'
},
toggleStatus : function(){
this.model.toggleStatus();
}
})