Search code examples
backbone.js

simple backbone events not firing


I'm playing around with backbone.js for the first time, but can't get the events to fire properly. Can somebody explain what I'm doing wrong?

Much appreciated!

in app.js loaded at the bottom of my html:

var Discussion = Backbone.Model.extend({
    defaults: {
        id: null,
        title: 'New discussion'
    },
    urlRoot: '/api/discussion'
});

var DiscussionCollection = Backbone.Collection.extend({
    model: Discussion,
    url: '/api/discussion'
});

var DiscussionView = Backbone.View.extend({   
   events: {
        'click .btnCreateDiscussion': 'create',
        'keypress #discussion_title': 'create'
   },

   initialize: function(){
        //this.$el = $("#form_discussion");
        this.template = _.template( $('#discussion-template').html() );
   },

   render: function(){
        console.log("rendering");
        return this;    
   },

   create: function(){
        console.log('creating a new discussion')
   }
});

var discussionView = new DiscussionView({ el: $("#form_discussion"), model: Discussion });

html:

<form action="" id="form_discussion" method="post">

<label for="discussion_title">Discussion Title</label>
<input type="text" id="discussion_title" name="discussion_title" />

<input class="btnCreateDiscussion" type="button" value="Create Discussion">

  <script type="text/template" id="discussion-template">
    <h1><%= title %></h1>
  </script>

Solution

  • The problem was jQuery. The most recent 1.x release didn't work, but using the most recent 2.x release fixes the problem. It would be useful if anyone could explain why we should only use 2.x in this case?