Calling a function from within itself - javascript

I have several elements inside a container. All their events are handled inside a function events().
On click of a button inside the container, I replace the container's html with the response from an AJAX request.
function events() {
$(".btn").on("click", function() {
...
});
$(".txt").on("keyup", function() {
...
});
$(".btn2").on("click", function() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
$(".container").html(xmlhttp.responseText);
events(); // ***
}
}
url = 'handlers/gethtml.ashx';
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
});
}
Now, I need to rebind all the controls with events so after changing the html $(".container").html(xmlhttp.responseText); I call the function within itself because the new html contains the same controls with the same events.
Does this cause stack overflow? I have some performance issues so i was wondering if this maybe the cause. Also, is there any workaround, maybe a more elegant way to do this?

Try using event delegation, you don't need to bind the event again
$(".container").on("click",".btn2", function() {...});
http://api.jquery.com/on/
http://learn.jquery.com/events/event-delegation/

Use event delegation, then no need to rebind the events since it will handle dynamic element as well
You could further shorten the code by using jquery to load the url contents
function events() {
var ct = $(".container");
ct.on("click", ".btn", function() {
});
ct.on("keyup", ".txt", function() {
});
ct.on("click", ".btn2", function() {
ct.load('handlers/gethtml.ashx')
}

Just call events(). It is in the scope!
There are a couple of things you need to be aware of, though:
Elements already on there will have two click handlers on the second run - the old, and the new. To get rid of them, use unbind to unbind all click events, for example.
You may want to split up your event creation function further.

Related

Remove Event Listener In an Object Literal Lost this reference

Currently working on a small project using an OLOO style approach.
Problem found here
So the issue I am facing is that I have an event handler.
eventHandler: function() {
console.log('Hit');
testSelector.removeEventListener('click', this.eventHandler, false);
}
Now what happens is that I want this to be removed after the first click. However this does not seem to work as I expected. I am binding the object this reference yet there seems to be something that I am missing in what is actually going on here. Would anyone be able to clarify what is actually happening or where I went wrong?
I'm not an expert in OLOO, but I can see two issues in your example:
the this inside an eventListener callback handler refers to the node so you need to take care you're referencing the same this in both methods ( add/removeEventListener )
removeEventListener won't work if the listener parameter isn't the same as addEventListener, and when you use bind you're actually creating a new function (so you have to keep track of that to)
in code:
var testSelector = document.querySelector('.test');
var object = {
init: function() {
this.ref = this.eventHandler.bind(this)
testSelector.addEventListener('click', this.ref, false);
},
eventHandler: function() {
console.log('Hit');
testSelector.removeEventListener('click', this.ref, false);
}
}
object.init();
https://jsbin.com/hejenuraba/1/edit?js,console,output
I got it to work in my environment as follows:
var testSelector;
var eventHandler = function(){
console.log('Hit');
testSelector.removeEventListener('click', eventHandler, false);
}
$(document).ready(function(){
testSelector = this.getElementById('btn');
testSelector.addEventListener('click',eventHandler);
});
You code looks fine but you may want to cross check the following:
In your line of code:
testSelector.removeEventListener('click', this.eventHandler, false);
Make sure you have the references to testSelector and eventHandler

In IE8: Create a custom event in vanilla JS and pick it up in Jquery

All of this is happening for IE8.
Due to script import orders, I'm having a bit of code being executed before JQuery is loaded where I need to fire a custom event.
This event will be picked up later in another bit of code when I'm sure JQuery will have been loaded. So I'd like to use JQuery to pick up this event.
I saw this previously asked question: How to trigger a custom javascript event in IE8? and applied the answer, which worked, but when I'm trying to pick up the Event via JQuery, then nothing happens.
Here's what I've tried:
function Event() {}
Event.listen = function(eventName, callback) {
if (document.addEventListener) {
document.addEventListener(eventName, callback, false);
} else {
document.documentElement.attachEvent('onpropertychange', function(e) {
if (e.propertyName == eventName) {
callback();
}
});
}
};
Event.trigger = function(eventName) {
if (document.createEvent) {
var event = document.createEvent('Event');
event.initEvent(eventName, true, true);
document.dispatchEvent(event);
} else {
document.documentElement[eventName] ++;
}
};
Event.listen('myevent', function() {
document.getElementById('mydiv-jquery').innerText = "myevent jquery";
});
$(document).on('myevent', function() {
document.getElementById('mydiv-vanilla').innerText = "myevent vanilla";
});
Event.trigger('myevent');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv-jquery">Nothing</div>
<div id="mydiv-vanilla">Nothing</div>
PS: The snippet doesn't seem to work properly in IE. Here's a jsfiddle that should be working.
There are a few problems with this code.
You shadow the built-in window.Event without checking if it exists; this could cause problems for other scripts.
You don't preserve the this binding when calling the callback from your onpropertychange listener. You should apply the callback to the document rather than calling it directly so the behavior will be as close as possible to addEventListener.
You attempt to increment document.documentElement[eventName] while it is undefined. The first call will change the value to NaN, so onpropertychange should pick it up, but on subsequent calls it will remain NaN.
You make no attempt to have .on() recognize your Event.listen function, so naturally the code in Event.listen will never be executed from a listener attached with .on().
Have you tried using Andrea Giammarchi's CustomEvent shim?

Multiple OnBeforeUnload

I am writing a JS which is used as a plugin. The JS has an onbeforeunload event.
I want suggestions so that my onbeforeunload event doesn't override the existing onbeforeunload event (if any). Can I append my onbeforeunload to the existing one?
Thanks.
I felt this has not been answered completely, because no examples were shown using addEventListener (but The MAZZTer pointed out the addEventListener solution though). My solution is the same as Julian D. but without using jQuery, only native javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Before Unload</title>
</head>
<body>
<p>Test</p>
<script>
window.addEventListener('beforeunload', function (event) {
console.log('handler 1')
event.preventDefault()
event.returnValue = ''
});
window.addEventListener('beforeunload', function (event) {
console.log('handler 2')
});
</script>
</body>
</html>
In this example, both listeners will be executed. If any other beforeunload listeners were set, it would not override them. We would get the following output (order is not guaranteed):
handler 1
handler 2
And, importantly, if one or more of the event listener does event.preventDefault(); event.returnValue = '', a prompt asking the user if he really wants to reload will occur.
This can be useful if you are editing a form and at the same time you are downloading a file via ajax and do not want to lose data on any of these action. Each of these could have a listener to prevent page reload.
const editingForm = function (event) {
console.log('I am preventing losing form data')
event.preventDefault()
event.returnValue = ''
}
const preventDownload = function (event) {
console.log('I am preventing a download')
event.preventDefault()
event.returnValue = ''
}
// Add listener when the download starts
window.addEventListener('beforeunload', preventDownload);
// Add listener when the form is being edited
window.addEventListener('beforeunload', editingForm);
// Remove listener when the download ends
window.removeEventListener('beforeunload', preventDownload);
// Remove listener when the form editing ends
window.removeEventListener('beforeunload', editingForm);
You only need to take care of this if you are not using event observing but attach your onbeforeunload handler directly (which you should not). If so, use something like this to avoid overwriting of existing handlers.
(function() {
var existingHandler = window.onbeforeunload;
window.onbeforeunload = function(event) {
if (existingHandler) existingHandler(event);
// your own handler code here
}
})();
Unfortunately, you can't prevent other (later) scripts to overwrite your handler. But again, this can be solved by adding an event listener instead:
$(window).unload(function(event) {
// your handler code here
});
My idea:
var callbacks = [];
window.onbeforeunload = function() {
while (callbacks.length) {
var cb = callbacks.shift();
typeof(cb)==="function" && cb();
}
}
and
callbacks.push(function() {
console.log("callback");
});
Try this:
var f = window.onbeforeunload;
window.onbeforeunload = function () {
f();
/* New code or functions */
}
You can modify this function many times , without losing other functions.
If you bind using jQuery, it will append the binding to the existing list, so there is no need to worry.
From the jQuery Docs on() method:
As of jQuery 1.4, the same event handler can be bound to an element
multiple times.
function greet(event) { alert("Hello "+event.data.name); }
$("button").on("beforeunload", { name: "Karl" }, greet);
$("button").on("beforeunload", { name: "Addy" }, greet);
You can use different javascript frameworks like jquery or you could probably add a small event add handler to do this. Like you have an object thatcontains a number of functions that you have added and then in the onbefore unload you run the added functions. So when you want to add a new function to the event you add it to your object instead.
something like this:
var unloadMethods = [];
function addOnBeforeUnloadEvent(newEvent) { //new Event is a function
unloadMethods[unloadMethods.length] = newEvent;
}
window.onbeforeunload = function() {
for (var i=0; i<unloadMethods.length; i++) {
if(typeof unloadMethods[i] === "function") {unloadMethods[i]();}
}
}
Those frameworks mentioned use addEventListener internally. If you are not using a framework, use that.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
For older versions of IE you should have a fallback to use attachEvent instead:
http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx
I liked Marius's solution, but embellished on it to cater for situations where the var f is null, and to return the first string returned by any function in the chain:
function eventBeforeUnload(nextFN){
//some browsers do not support methods in eventAdd above to handle window.onbeforeunload
//so this is a way of attaching more than one event listener by chaining the functions together
//The onbeforeunload expects a string as a return, and will pop its own dialog - this is browser behavior that can't
//be overridden to prevent sites stopping you from leaving. Some browsers ignore this text and show their own message.
var firstFN = window.onbeforeunload;
window.onbeforeunload = function () {
var x;
if (firstFN) {
//see if the first function returns something
x = firstFN();
//if it does, return that
if (x) return x;
}
//return whatever is returned from the next function in the chain
return nextFN();
}
}
In your code where required use it as such
eventBeforeUnload(myFunction);
//or
eventBeforeUnload(function(){if(whatever) return 'unsaved data';);

How can I call a JavaScript function after every a4j AJAX response?

I am working on a web app using JSF w/Seam. I want to be able to call a JavaScript function after every ajax response. I'm looking for a way to do this without putting an oncomplete attribute on every commandLink/commandButton on every page.
I think there's a way to set up a servlet filter (interceptor? I get the terms confused) to inject the JS call into each response. I'm going to look into that. In the meantime, if anyone has any other suggestions, I'm all ears.
EDIT: I think the jQuery ajaxSuccess method might be the way to go here, but I'm not sure how to actually use it. I can't get anything to register. I basically want to add code to get any and all ajax requests from any source to call my JavaScript method on success. Can anyone show me the proper way to do this? I've tried a number of ways to do this, including adding jQuery("*").ajaxSuccess(function(){myFunction();}); to the bottom of my template xhtml file.
Rewritten answer: see original answer in revision history
You could override the default send method of XMLHttpRequest with one that hijacks the readystatechange handler:
(function ()
{
var xhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function ()
{
var handler = this.onreadystatechange;
this.onreadystatechange = function ()
{
if (handler) {
if (handler.handleEvent) handler.handleEvent.apply(xhr, arguments);
else handler.apply(xhr, arguments);
}
if (this.readyState == 4)
{
// your oncomplete function here
this.onreadystatechange = handler;
}
};
xhrSend.apply(this, arguments);
};
})();
Edit: The above function doesn't work with jQuery requests, and so potentially it could fail with other libraries as well. The revision below addresses the issue with a setTimeout hack to delay the code that overrides the handler. Of course, with jQuery, you can just use the .ajaxSuccess() global handler, but for other libraries with similar behavior, this would be useful.
(function() {
function globalHandler() {
if (this.readyState == 4) {
// your oncomplete code here
}
}
var xhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
var xhr = this;
if (xhr.addEventListener) {
xhr.removeEventListener("readystatechange", globalHandler);
xhr.addEventListener("readystatechange", globalHandler, false);
}
else {
function readyStateChange() {
if (handler) {
if (handler.handleEvent)
handler.handleEvent.apply(xhr, arguments);
else
handler.apply(xhr, arguments);
}
globalHandler.apply(xhr, arguments);
setReadyStateChange();
}
function setReadyStateChange() {
setTimeout(function() {
if (xhr.onreadystatechange != readyStateChange) {
handler = xhr.onreadystatechange;
xhr.onreadystatechange = readyStateChange;
}
}, 1);
}
var handler;
setReadyStateChange();
}
xhrSend.apply(xhr, arguments);
};
})();
http://jsfiddle.net/gilly3/FuacA/5/
I tested this in IE7-9, and the latest versions of Chrome and FF
Since you are using RichFaces you can simply use this:
<a:status id="globalStatus" onstart="onRequestStart()" onstop="onRequestEnd()" />
Using a4j:status should work, but it has to be inside an h:form tag:
<h:form id="randomForm" styleClass="edit">
<a:status id="stateStatus"
onstart="Richfaces.showModalPanel('waitBx'),document.getElementById('randomForm:search').disabled=true;"
onstop="Richfaces.hideModalPanel('waitBx'),document.getElementById('randomForm:search').disabled=false;"
styleClass="message" >
</a:status>
...... way more code
</form>
After every ajax call this pops up a wait picture and disables the search button.
Interestingly enough, at least in our code, this doesn't work for anything in a nested a4j:region.
I think this is what you are looking for: Using Global Ajax Handlers In jQuery

How to override JavaScript function from a Firefox extension?

I am trying to intercept calls to document.write for all pages. Setting up the interception inside the page by injecting a script like
function overrideDocWrite() {
alert("Override called");
document.write = function(w) {
return function(s) {
alert("special dom");
w.call(this, wrapString(s));
};
}(document.write);
alert("Override finished");
}
Is easy and works, but I would like my extension to setup the interception for each document object from inside the extension. I couldn't find a way to do this. I tried to listen for the "load" event and set up the interception there but it also fails. How do I hook calls to doc.write from an extension?
I made some progress:
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent)
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad,
true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
// do something with the loaded page.
// doc.location is a Location object (see below for a link).
// You can use it to make your code executed on certain pages only.
alert("Override called");
alert(doc);
alert(doc.write);
alert(doc.wrappedJSObject);
alert(doc.wrappedJSObject.write);
doc.wrappedJSObject.write = function(w) {
return function(s) {
alert("special dom");
w.call(this, "(" + s + ")");
};
}(doc.write);
alert("Override finished");
}
}
This seem to work, but DOMContentLoaded is the wrong event for the job, because it is fired too late! Is there an earlier event to listen to?
Ressurection of the question ! I got the answer. Here is a sample code :
const os = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
os.addObserver({
observe : function(aWindow, aTopic, aData) {
if (aWindow instanceof Ci.nsIDOMWindow && aTopic == 'content-document-global-created') {
aWindow.wrappedJSObject.myfunction = function(){
// Do some stuff . . .
}
}
}
}, 'content-document-global-created', false);
The same goes for document with the event document-element-inserted as of gecko 2.0 .
JavaScript uses a prototypical inheritance system, instead of having classes, objects have prototypes. Prototypes are real objects that are used as a reference to other objects for inheritance of methods and attributes.
The best strategy would be to override the method write in the prototype of "document" (which for the HTML document is HTMLDocument). This should effectively wrap the method for all instances of "document" inside the pages loaded in the browser since they all use the same prototype.
Instead of
document.write = function() { ... }
try something like this:
HTMLDocument.prototype.write= function() { ... }
UPDATE: It does not seem to be as easy as I initially thought, this does not seem to work at first try.

Categories

Resources