0
votes

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
1
sorry, think that's a copy/paste issue with markdown. #add is contained within a div under #booksgh0st
changed it to <button type="button"> which stopped the page reloads, but it's still not registering the click event. Also, not sure if this is related at all, but I'm getting a 404 on backbone-min.mapgh0st
yes, I'm pretty sure it is. I see it devtools when I examine the page elements. would how my files are organized cause an issue if the html file that contains #books is organized like so: jsfiddle.net/66HSU/1gh0st

1 Answers

1
votes

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