不久前,我在Stackoverflow上发布了this个问题。基本上,这是我第一次尝试在自己的项目中试用Backbone.js,之前的帖子问题已经解决了。
但是现在,在加载此页面时,我可以看到Chrome控制台窗口中打印了以下javascript错误。
Uncaught ReferenceError: completed is not defined VM46:6
(anonymous function) VM46:6
_.template.template underscore.js:1308
Backbone.View.extend.render example_addbutton.html:69
Backbone.View.extend.initialize example_addbutton.html:65
Backbone.View backbone.js:1031
child backbone.js:1658
(anonymous function)
在花了一个小时的故障排除后,我将问题追溯到代码的这一部分。
<script id="taskTemplate" type="text/template">
<span class="<%=completed ? 'completed' : 'incomplete' %>"><%= text %></span>
<button class="complete"></button>
<button class="delete"></button>
</script>
这表明Underscore的模板引擎无法理解&#39;已完成&#39;变量
当我在这里宣布它时,怎么可能呢?
var Tasks = Backbone.Collection.extend({
model: Task,
completed: function(){
return _.filter(this.models, function(model){
return model.get('completed');
});
},
});
我做错了什么?
答案 0 :(得分:0)
终于找到了解决方案。
在网上挖掘快速解决方案之后,我不得不重构所谓的“教程”代码以使应用程序正常工作。
原来它的Backbone View逻辑编写得不好,因为它试图呈现主应用程序屏幕以及代码的一部分中添加的新项目。所以我不得不把它拿出来放在另一个Backbone View Logic中,并附带相应的事件监听器。
var TasksView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#taskTemplate').html()),
events: {
'click .delete': 'delete',
'click .complete': 'updateStatus',
'dblclick span': 'edit'
},
initialize: function(){
this.model.on('change', this.render, this);
this.model.on('remove', this.unrender, this);
this.render();
},
render: function(){
var markup = this.template(this.model.toJSON());
this.$el.html(markup);
return this;
},
unrender: function(){
this.$el.remove();
},
delete: function(){
this.model.destroy();
this.$el.remove();
},
updateStatus: function(){
this.model.set('completed', !this.model.get('completed'));
},
edit: function(){
var text = prompt('What should we change your task to?', this.model.get('text'))
this.model.set('text',text);
},
});
var AppView = Backbone.View.extend({
el:'#tasks',
events: {
'click .add': 'add',
'click .clear': 'clearCompleted'
},
initialize: function(){
this.collection = new Tasks();
this.collection.on('add', this.addOneTask, this);
this.items = this.$el.children('ul');
},
add: function(){
var text = prompt('What do you need to do?');
var task = new Task({text: text});
this.collection.add(task);
},
render: function(){
},
addOneTask: function(task){
var view = new TasksView({model:task});
this.items.append(view.render().el);
},
clearCompleted: function(){
var completedTasks = this.collection.completed();
this.collection.remove(completedTasks);
}
});
瞧!它有效!