javascriptbackbone.jsbackbone-eventsicanhaz.jsbackbone-views

Backbone.js View Event Not Firing


I am having problems getting my backbone.js view events to fire. When I click #login-button nothing is happening.

I am also using iCanHaz (http://icanhazjs.com/) to load the templates.

Here is my javascript:

$(function() {
 var router = new App.Router;
 Backbone.history.start();
});

App.Router = Backbone.Router.extend({
 routes: {
    "login": "login"
 },

login: function() {
    var view = new App.Views.LoginView;
 }
});

App.Views.LoginView = Backbone.View.extend({

 el: '#login',

 initialize: function() {

    _.bindAll(this, 'render', 'validateLogin');
    this.render();

 },

 render: function() {
    App.Stage.html(ich.loginView());
 },

 events: {
    'click button#login-button' : 'validateLogin'
 },

 validateLogin: function(event) {
     console.log("validateLogin fired.");
 }

});

Here is my markup (using ICanHaz.js):

<script id="loginView" type="text/html">
        <div data-role="page" id="login" class="container">
            <div class="hero-unit">
                <div class="row-fluid">
                    <div class="span12">
                        <div class="form-horizontal">
                        <fieldset>
                            <legend>Please login to continue</legend>
                            <div class="control-group">
                            <label class="control-label" for="username">Username</label>
                            <div class="controls">
                                <input type="text" class="input-xlarge" id="username">
                            </div>
                            </div>

                                <div class="control-group">
                            <label class="control-label" for="password">Password</label>
                            <div class="controls">
                                <input type="password" class="input-xlarge" id="password">
                            </div>
                            </div>

                                <div class="form-actions">
                        <button id="login-button" class="btn btn-primary btn-large">Login</button>
                    </div>
                        </fieldset>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </script>

Solution

  • I figured it out. Backbone was binding the events to the el before it was created. In the callback for the asynchronous iCanHaz call, I used this.setElement('#login') and it worked perfectly. From the backbone.js documentation:

    setElement [view.setElement(element)]
    

    "If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one."