Search code examples
javascriptbackbone.jsbackbone-events

Backbone: Event handler not defined?


I am reading Developing Backbone Applications and following with the Todo example. However when I run the following code, there is an error:

Uncaught ReferenceError: createOnEnter is not defined.

What? It is defined and I cannot figure out what's wrong?

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();

Solution

  • You need to wrap each method name with quotes:

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