Search code examples
javascriptbackbone.js

Backbone asynchronous view instantiations


I would need to do something like this:

new app.view().done(function() {})

That's because I am setting the view element asynchronously in the initialize function and I need to use the element right after the instantiation.

If I do this it doesn't work:

var view = new app.view();
var $el = view.$el;

Because the view element isn't ready yet.

Again, I need something like this:

new app.view().done(function(view) {
    var $el = view.$el;
})

But I can't find any ways to do this. Would overriding the constructor help me with this?


Solution

  • Option 1 - Backbone.Events - example

    You could trigger an event after the $el has been asynchronously created like this:

    app.view = Backbone.view.extend({
        initialize: function ()
        {
            // async setup the $el and then do the following after it is created
            this.trigger('el:created', this.$el);
        }
    });
    

    And then all other views can listen to this event and act accordingly:

    app.anotherView = Backbone.view.extend({
        initialize: function ()
        {
            var otherView = new app.view();
    
            // Only fires once so only listen once
            this.listenToOnce(otherView, 'el:created', this.createEl);
        },
    
        createEl: function ($el)
        {
            //do something with $el here
        }
    });
    

    Option 2 - jQuery.Deffered - example

    app.view = Backbone.view.extend({
        initialize: function ()
        {
            this.elCreation = $.Deferred();
    
            // async setup the $el and then do the following after it is created
            this.elCreation.resolve(this.$el);
        }
    });
    
    new app.view().elCreation.done(function($el)
    {
        //do something with $el here
    });