javascript - Backbone : Event handler not defined?

标签 javascript backbone.js backbone-events

我正在阅读Developing Backbone Applications 并遵循Todo 示例。 但是当我运行下面的代码时,出现了一个错误:

Uncaught ReferenceError: createOnEnter is not defined.

什么?它已定义,但我不知道哪里出了问题?

var app = {};

app.Todo = Backbone.Model.extend({
  defaults: {
    title: "",
    text: ""
  },

  toggle: function(){
    this.save({
        closed: !this.get('closed')
    });
  }
}); 

var TodoList = Backbone.Collection.extend({
    model: app.Todo,

    localStorage: new Backbone.LocalStorage('todos-backbone'),
    closed: function(){
       return this.filter(function(todo){
        return todo.get('closed');
       });
    },

    open: function(){
        return this.without.apply(this, this.closed());
    }
 });  

app.Todos = new TodoList();

app.TodosView = Backbone.View.extend({

el: '#query-chat-main',

events: {
    'click #save-todo': createOnEnter,
    'click #clear-todos': cleartodos,
    'click #close-todos': closetodos
},

initialize: function(){
    this.$title = this.$('#todo-title');
    this.$text = this.$('#todo-text');
    
    this.listenTo(app.todos, 'add', this.addtodo);
    this.listenTo(app.todos, 'reset', this.addtodos);
    
    app.todos.fetch();
},

render: function(){
    var closed = app.todos.closed().length;
    var open = app.todos.open().length;
},

addtodo: function(todo){
    //var view = new app.TodoView({model: todo});
    $('#todos').append(view.render().el);
},

addtodos: function(){
    this.$('#todos').html('');
    app.todos.each(this.addtodo, this);
},

newAttributes: function(){
    return {
        title: this.$title.val().trim(),
        text: this.$text.val().trim(),
        closed: false
    };
},

createOnEnter: function(e){
    e.preventDefault();
    app.todos.create(this.newAtrributes());
    this.$title.val('');
    this.$text.val('');
},

cleartodos: function(e){
    e.preventDefault();
    _.invoke(app.todos.closed(), 'destroy');
},

closetodos: function(e){
    e.preventDefault();
    app.todos.each(function(todo){
        todo.save({
            closed: true
        });
    });
}

});


new app.TodosView();

最佳答案

您需要用引号将每个方法名括起来:

events: {
    'click #save-todo': 'createOnEnter',
    'click #clear-todos': 'cleartodos',
    'click #close-todos': 'closetodos'
},

关于javascript - Backbone : Event handler not defined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26571989/

相关文章:

javascript - Add 按钮将生成新的 Textarea

javascript - 在 Object.create() 中定义函数

javascript - Backbone.js 未捕获类型错误 this.model.each 不是函数

javascript - 使用 Backbone.js 显示 Div

backbone.js - 可配置的 Backbone.js 事件选择器

javascript - 由多个外部元素触发的主干 View

javascript - 通过 POST 调用 HTML Javascript 函数

java - 有没有一种方法可以使用通用代码库在 Java 和 JavaScript 中进行输入验证?

javascript - Backbone.js 集合

internet-explorer - Adsense 广告未显示在 IE 中(IE浏览器)