When to apply jQuery code in a Backbone view

I have the following basic 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 problem is that when I do: $ ('# username'). focus () ;: in the render, this is: usernameFocus: the event is not connected yet. There are only two solutions that I can think of.

  • Use setTimeout - while this parameter will technically work, I do not consider it a real option
  • Manually apply events in rendering. Doing this will completely complete the event system provided by Backbone, which seems weird.

Does Backbone provide a way to run jQuery code after applying all the events?

+3
source share
2 answers

, , , - , Backbone. :

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

.

+1

, , .

+1

All Articles