Question

I have the following view and I'm trying to bind a click event to a button with the id of #add. However, it won't even register the preventDefault function.

var app = app || {};

app.LibraryView = Backbone.View.extend({
el: '#books',

events: {
    'click #add' : 'addBook'
},

initialize: function() {
    this.collection = new app.Library();
    this.render();
    this.listenTo( this.collection, 'add', this.renderBook);

},

render: function() {
    this.collection.each(function( item ) {
        this.renderBook( item );
    }, this );
},

renderBook: function( item ) {
    var bookView = new app.BookView({
        model: item
    });
    this.$el.append( bookView.render().el );
},

addBook: function(e) {
    e.preventDefault();
    var formData = {};
    $('#addBook div').children('input').each(function(index, el) {
      if($(el).val() != '') {
        formData[el.id] = $(el).val();
      }
    });

    this.collection.add(new app.Book(formData));
    console.log("book added");
}


});

Also, I can call renderBook in the console and it will add a new bookView, however, the render function doesn't seem to be working when the page loads initially.

Here is my html in jade.

block content
#books
  form#addBook(action'#')
    div
      label(for='coverImage').span5 Image URL:
      input#coverImage(type='text')
      label(for='title').span5 Title:
      input#title(type='text').span5
      label(for='author') Author:
      input#author(type='text').span5
      label(for='date') Date:
      input#date(type='text').span5
      label(for='tags') Tags:
      input#tags(type='text').span5
      button#add Add


.bookContainer
  ul
   li Title
   li Author
   li Date
  button Delete
Was it helpful?

Solution

You have to instantiate your view new app.LibraryView() in order for your view's events to be binds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top