Question

There wasn't something close enough to this already... at least that my newbie mind could grasp.

I'm just trying to play around creating a global containing object that has methods, and contained within are the instructions to create and use AJAX requests. I then proceed to create an event listener for a button. I then get the following console output.

Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Uncaught ReferenceError: globOject is not defined script.js:21
Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Exception in onResRdy: TypeError: Cannot read property 'htmlRes' of undefined ContentScript.js:84

I'm sure I'm doing a lot wrong here. Let me know what additional info I would need to include to get assistance on this.

var globObject = {
sendToServer: function () {
    alert('you got to me at least!');
    var xhr;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xhr=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xhr=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.open('POST', 'counterDoc.php', true);
    xhr.send();
},
counterClick: function (counter) {
    alert('you got here!');
    counter += 1;
    this.sendToServer();
}};
var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0), true);
Was it helpful?

Solution

  1. Fix the typo I said in comment and also @Bonakid mentioned. globOject.counterClick(0), true); should be globObject.counterClick(0), true);

  2. Do not use globObject.counterClick(0) for callback function, use globObject.counterClick instead. The first one will get called immediately when globObject is defined.

  3. Do not use this.sendToServer();, use globObject.sendToServer(); instead. this in the counterClick method will be document.getElementById('submbut') which is a HTML element. Add console.log(this) to counterClick and you will see that.

A working demo here

OTHER TIPS

change this

var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0)

to

var button = document.getElementById('submbut').addEventListener('click',globObject.counterClick(0)

theres a typographical error in this part

globOject.counterClick(0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top