无法在浏览器中显示待办事项列表视图

Unable to display TodoList view in browser

本文关键字:列表 视图 显示 浏览器      更新时间:2023-09-26

我正在学习Backbone JS,我正在尝试显示TodosList,但不渲染。但是,我能够从服务器获取集合数据。

你能告诉我下面的代码出了什么问题吗?

这是代码:

<html>
<head>
<link rel="stylesheet"
    href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
</head>
<body>
<div id="demo"></div>
<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({
    urlRoot: 'api',
})
var TodoCollection = Backbone.Collection.extend({
    model: TodoItem,
    url: 'api/todos'
})

var TodoView = Backbone.View.extend({
    initialize: function(){
        this.listenTo(this.collection,'fetch',this.render)
        this.collection.fetch()
    },
    render: function(){
        this.collection.forEach(this.addOne,this)
    },
    addOne: function(todoItem){
        console.log(todoItem.get('status'))
    }
})

var todoItem = new TodoItem()
var todoList = new TodoCollection()
var todoView = new TodoView({el: '#demo', collection: todoList})
todoView.render()
console.log(todoView.el)

</script>
</body>
</html>

而且我不确定"获取"是否是预定义的事件?何时使用"重置"事件,何时使用"获取"事件?他们看起来都和我相似。

没有'fetch'事件,因此您的listenTo不会执行任何有用的操作。通常,当您fetch整个集合时,您会重置它:

this.collection.fetch({ reset: true });

然后侦听'reset'事件:

this.listenTo(this.collection, 'reset', this.render);

fetchreset:true选项告诉fetch在一个操作中将集合的内容完全替换为获取的数据;然后集合将在fetch全部完成时触发'reset'事件,并且您的侦听器将其转换为render调用。

您的initialize应该更像:

initialize: function(){
    this.listenTo(this.collection, 'reset', this.render);
    this.collection.fetch({ reset: true });
}