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.
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:When you call
o.mthrough the plain functionf,thisinsideo.mwill usually be the global context (windowin a browser). You can also useapplyandcallto choose a differentthisso this:would make
thistheothat you’d expect it to be. I should mention that you can force your choice ofthisusingbindin most JavaScript environments but I don’t want to get too sidetracked.The point is that this:
isn’t enough to ensure that
showLoaderandhideLoaderwill run in the right context; I’m also assuming that the parentheses you had at the end ofshowLoaderandhideLoaderwere just typos.The most common way to force a context in a Backbone application is to use
_.bindAllin yourinitialize:That essentially replaces
this.showLoaderandthis.hideLoaderwith something that’s, more or less, equivalent to your wrappers:Once you have that
_.bindAllin place, this:will work fine.
BTW, you don’t need to do this:
in your
initialize, Backbone does that for you:And you don’t need to do things like this:
either, Backbone gives you a
$method in your view that does the same thing without hiding theelat the end of the argument list; doing it like this:is more idiomatic in Backbone.
Furthermore,
this.elwon’t necessarily be a jQuery object so don’t do this:in your
render, use the cachedthis.$elinstead: