我正在尝试在浏览器中运行我的 js 应用程序,但是当我这样做时,我在控制台中收到此错误:
“未捕获的类型错误:未定义不是函数”app.js:18
我已阅读并尝试了类似问题的其他答案,但没有成功。
第 18 行错误的代码:
var AppView = Backbone.View.extend({
el: $("#todoapp"),
statsTemplate: _.template($('#stats-template').html()),
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
initialize: function() {
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
this.listenTo(Todos, 'add', this.addOne); //the line with the error
this.listenTo(Todos, 'reset', this.addAll);
this.listenTo(Todos, 'all', this.render);
this.footer = this.$('footer');
this.main = $('#main');
Todos.fetch();
},
render: function() {
var done = Todos.done().length;
var remaining = Todos.remaining().length;
if (Todos.length) {
this.main.show();
this.footer.show();
this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
} else {
this.main.hide();
this.footer.hide();
}
this.allCheckbox.checked = !remaining;
},
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
addAll: function() {
Todos.each(this.addOne, this);
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
},
clearCompleted: function() {
_.invoke(Todos.done(), 'destroy');
return false;
},
toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); });
}
});
这是我的 collection.js 代码:
var TodoList = Backbone.Collection.extend({
model: Todo,
localStorage: new Backbone.LocalStorage("todos-backbone"),
done: function(){
return this.where({done: true});
},
remaining: function(){
return this.without.apply(this, this.done());
},
nextOrder: function(){
if (!this.length) return 1;
return this.last().get('order')+1;
},
comparator: 'order'
});
var Todos = new TodoList();
最佳答案
如果您想使用listenTo
,您需要升级您的Backbone版本。来自 fine ChangeLog :
0.9.9 — Dec. 13, 2012
- Added listenTo and stopListening to Events. They can be used as inversion-of-control flavors of
on
andoff
, for convenient unbinding of all events an object is currently listening to.view.remove()
automatically callsview.stopListening()
.
listenTo
方法出现在 Backbone 0.9.9 中,但您使用的是 0.9.1。
阅读变更日志并升级您的 Backbone 版本。
关于javascript - 主干应用 View 中的 “Uncaught TypeError: undefined is not a function”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23554828/