Saif Bechan
Saif Bechan

Reputation: 17131

Why Backbone.js isn't binding my event

I have a router like this, as main entry point:

window.AppRouter = Backbone.Router.extend({
    routes: {
        '': 'login'
    },
    login: function(){

        userLoginView = new UserLoginView();
    }
});

var appRouter = new AppRouter;
Backbone.history.start({pushState: true});

I have a model/collection/view like this:

window.User = Backbone.Model.extend({});

window.Users = Backbone.Collection.extend({
    model: User
});

window.UserLoginView = Backbone.View.extend({

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

    initialize: function(){
        _.bindAll(this, 'render', 'loginAction');
    },

    loginAction: function(){
        var uid = $("#login-username").val();
        var pwd = $("#login-password").val();

        var user = new User({uid:uid, pwd:pwd});
    }
});

And body of my HTML looks like this:

<form action="#" method="POST" id="login-form">
    <p>
        <label for="login-username">username</label>
        <input type="text" id="login-username" autofocus />
    </p>
    <p>
        <label for="login-password">password</label>
        <input type="password" id="login-password" />
    </p>
    <a id="login-button" href="#">Inloggen</a>
</form>

Note: The HTML comes from Node.js using express.js, should I maybe wait for a document ready event somewhere?

Edit:

I have tried this, create the view when ready, did not solve the problem.

    $(function(){
        userLoginView = new UserLoginView();
    });

Upvotes: 0

Views: 996

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55678

It doesn't look from the code you've posted like you're assigning an el property to the UserLoginView instance. I don't think the events hash will work to bind event handlers unless the view has an el (that is, a root DOM element for the view - see docs). When you initialize the view, it binds handlers to the root element, using .delegate() for child elements, so no root element, no handlers, even with id-based selectors. Try this:

window.UserLoginView = Backbone.View.extend({
    el: '#login-form',
    // etc
});

Note that, as discussed in the comments, you should be doing this after the DOM is ready. The standard approach here is to kick off the router and history machinery in $(document).ready:

$(function() {
    var appRouter = new AppRouter;
    Backbone.history.start({pushState: true});
});

Upvotes: 1

Related Questions