I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website.
Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating one of the DIVs within the Topbar. These functions are inherited from Container, of which Ribbon is an instance.
The functions MPP_Topbar.Ribbon.clear()
and
MPP_Topbar.Ribbon.load('default.xml')
are functioning correctly. However, there seems to be an issue with the callback function MPP_Topbar.Ribbon.insert()
, which is supposed to be triggered by the ajaxGet()
function once the xmlhttprequest is complete. For some reason, within the insert
class method, the reference to this
suddenly changes to point to window
instead of remaining within the parent object Ribbon
.
Is there a way for me to ensure that Ribbon
is referenced correctly within the insert
method?
The code for the Topbar script:
MPP_Topbar = {};
MPP_Topbar.Container = function(){};
MPP_Topbar.Container.prototype.clear = function(){
var element = this.element;
while (element.firstChild) {
element.removeChild(element.firstChild);
}
};
MPP_Topbar.Container.prototype.load = function(page){
this.clear();
ajaxGet(page, this.insert);
console.log('loading');
};
MPP_Topbar.Container.prototype.insert = function(content){
console.log(this);
this.element.innerHTML = content;
console.log('inserted');
};
MPP_Topbar.Ribbon = new MPP_Topbar.Container;
MPP_Topbar.Ribbon.element = document.getElementById('THERIBBON');
The AJAX request function:
function ajaxGet(file, callback, postdata, async){
async = ((async == true || async === undefined) ? true : false);
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(async){
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
callback(xmlhttp.responseText);
}
}
}
if(postdata){
xmlhttp.open("POST", file, async);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}else{xmlhttp.open("GET", file, async);}
xmlhttp.send();
}