Backbone:事件处理程序没有定义?

时间:2014-10-26 10:25:07

标签: javascript backbone.js javascript-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();

1 个答案:

答案 0 :(得分:2)

您需要用引号包装每个方法名称:

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