Search code examples
javascriptjquerybackbone.jsbackbone-events

When to apply jQuery code in a Backbone view


I have the follow backbone view:

core.views.Login = Backbone.View.extend(
{
    el: '#main-content-wrapper',

    events:
    {
        'focus #username': 'usernameFocus',
        'blur #username': 'usernameBlur'
    },

    initialize: function()
    {
        this.render();
    },

    render: function()
    {
        var html = unlocked.renderTemplate('login', 'core');
        this.$el.empty().html(html);

        $('#username').focus();

        return this;
    },

    usernameFocus: function(event)
    {
        console.log('focus');
        if($(event.target).val() == 'Username')
        {
            $(event.target).val('');
        }
    },

    usernameBlur: function(event)
    {
        if($(event.target).val() == '')
        {
            $(event.target).val('Username');
        }
    }
});

The issue I have is that when I do : $('#username').focus(); : in the render is that the : usernameFocus : event has not yet been attached. There are only two solutions I can think of.

  1. Use setTimeout - while this option would technically work, I don't consider it a real option
  2. Manually apply events in render - Doing this would completely by-pass the event system that Backbone provides which just seems weird.

Does Backbone provide me a way to run jQuery code after all events have been applied?


Solution

  • One simple way to get your event handlers mapped to the events prior to your focus setting code is to call the same binding code that Backbone itself provides. You should be able to call:

    this.delegateEvents();
    this.render();
    

    in your initialize and get the effect you wanted.