4
votes

I'm using backbone for an app that I'm building. In this app, I have a master view which render a template with 2 other views inside. One header view and another one with some content. The header view is just used to interact with the content view and has specific functions too.

In the header template and content template I have the same piece of code, an hidden DIV with a loader image that is displayed when an ajax call is made. The problem I have is that when I load the app for the first time (or when I refresh the content view), the content view is loading some data from an ajax request, but the loader is showing up in both the header and the content template (like if the ajaxStart() was a global event not attached to the view.

Here is the content view setup:

App.View.Content = Backbone.View.extend({
        type:'test',
        template: twig({
            href: '/js/app/Template/Content.html.twig',
            async: false
        }),
        block:{
            test:twig({
                href: '/js/app/Template/block/test.html.twig',
                async: false
            })
        },
        list:[],

        showLoader: function(el){
            console.log('loader: ', $('#ajax_loader', el));
            $('#ajax_loader', el).show();
            console.log('Ajax request started...');
        },

        hideLoader: function(el){
            $('#ajax_loader', el).hide();
            console.log('Ajax request ended...');
        },

        initialize: function(params)
        {
            this.el   = params.el;
            this.type = params.type || this.type;
            var self  = this;

            this.el
                .ajaxStart(function(){self.showLoader(self.el);})
                .ajaxStop(function(){self.hideLoader(self.el);});

            this.render(function(){
                self.list = new App.Collection.ListCollection();
                self.refresh(1, 10);
            });
        },

    refresh:function(page, limit)
    {
        var self = this;
        console.log('Refreshing...');

        $('#id-list-content').fadeOut('fast', function(){
            $(this).html('');
        });

        this.list.type  = this.type;
        this.list.page  = page || 1;
        this.list.limit = limit || 10;

        this.list.fetch({
            success: function(data){
                //console.log(data.toJSON());

                $.each(data.toJSON(), function(){
                    //console.log(this.type);
                    var tpl_block = self.block[this.type];
                    if (tpl_block != undefined) {
                        var block = tpl_block.render({
                            test: this
                        });
                        $(block).appendTo('#id-list-content');
                    }
                });

                $('#id-list-content').fadeIn('fast');
            }
        });
    },

    render: function(callback)
    {
        console.log('Rendering list...');
        this.el.html(this.template.render({

        }));

        if (undefined != callback) {
            callback();
        }
    }
});

As you can see I'm using an ugly piece of code to attach the ajaxStart / ajaxStop event:

this.el
    .ajaxStart(function(){self.showLoader(self.el);})
    .ajaxStop(function(){self.hideLoader(self.el);});

I use to have it like this:

this.el
    .ajaxStart(self.showLoader())
    .ajaxStop(self.hideLoader());

But for whatever reason that still undefined on my end, this.el was not defined in the showLoader() and hideLoader().

I was thinking that ajaxStart() and ajaxStop() was attached to the this.el DOM, and that only this view would be able to listen to it. But my headerView which has exactly the same setup (except for the twig template loaded) apparently receive the event and show the loader.

To be sure of this behavior, I've commented out the showLoader() in the content view, and the loader still show up in the header view.

I don't know what I'm doing wrong :(

EDIT (after answer from "mu is too short"):

my content view does now looks like this:

showLoader: function(){
            //this.$('#ajax_loader').show();
            console.log('Ajax request started...');
        },

        hideLoader: function(){
            this.$('#ajax_loader').hide();
            console.log('Ajax request ended...');
        },

        initialize: function(params)
        {
            var self  = this;

            console.log(this.el);

            _.bindAll(this, 'showLoader', 'hideLoader');

            this.$el
                .ajaxStart(this.showLoader)
                .ajaxStop(this.hideLoader);

            this.render(function(){
                self.list = new App.Collection.List();
                self.refresh(1, 10);
            });
        },
...

render: function(callback)
        {
            console.log('Rendering post by page...');
            this.$el.html(this.template.render({

            }));

            if (undefined != callback) {
                callback();
            }
}

and my header view:

...
showLoader: function(){
            this.$('#ajax_loader').show();
            //console.log('Ajax request started...');
        },

        hideLoader: function(el){
            this.$('#ajax_loader').hide();
            console.log('Ajax request ended...');
        },

        initialize: function(params)
        {
            var self = this;
            _.bindAll(this, 'showLoader', 'hideLoader');

            this.$el
                .ajaxStart(this.showLoader)
                .ajaxStop(this.hideLoader);

            this.models.Link = new App.Model.Link();
            this.render();
        },

        render: function(callback)
        {
            this.$el.html(this.template.render({
                data: []
            }));

            if (undefined != callback) {
                callback();
            }
        }
...

But the loader still showing up in the header view template

PS: this.showLoader() was not a typo as I wanted to call the function within the current backbone view.

1

1 Answers

3
votes

The context (AKA this) for a JavaScript function depends on how the function is called, not on the context in which the function is defined. Given something like this:

var f = o.m;
f();

When you call o.m through the plain function f, this inside o.m will usually be the global context (window in a browser). You can also use apply and call to choose a different this so this:

f.call(o);

would make this the o that you'd expect it to be. I should mention that you can force your choice of this using bind in most JavaScript environments but I don't want to get too sidetracked.

The point is that this:

this.el
    .ajaxStart(this.showLoader)
    .ajaxStop(this.hideLoader);

isn't enough to ensure that showLoader and hideLoader will run in the right context; I'm also assuming that the parentheses you had at the end of showLoader and hideLoader were just typos.

The most common way to force a context in a Backbone application is to use _.bindAll in your initialize:

initialize: function(params) {
    _.bindAll(this, 'showLoader', 'hideLoader');
    //...

That essentially replaces this.showLoader and this.hideLoader with something that's, more or less, equivalent to your wrappers:

function() { self.showLoader(self.el) }

Once you have that _.bindAll in place, this:

this.el
    .ajaxStart(this.showLoader)
    .ajaxStop(this.hideLoader);

will work fine.


BTW, you don't need to do this:

this.el = params.el;

in your initialize, Backbone does that for you:

constructor / initialize new View([options])

[...] There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.

And you don't need to do things like this:

$('#ajax_loader', el).show();

either, Backbone gives you a $ method in your view that does the same thing without hiding the el at the end of the argument list; doing it like this:

this.$('#ajax_loader').show();

is more idiomatic in Backbone.

Furthermore, this.el won't necessarily be a jQuery object so don't do this:

this.el.html(this.template.render({ ... }));

in your render, use the cached this.$el instead:

this.$el.html(this.template.render({ ... }));