I can set the onclick handler using jQuery by calling
$('#id').click(function(){
console.log('click!');
});
Also using jQuery, how can I get a reference to the function which is currently handling the click() event?
The reason is that I have another object and want to set its click handler to the same one as #id.
Update
Thank you for all the suggestions. The problem is that I do not know which function is currently handling the clicks. Keeping track of it would add state to an already complicated template-editing system.
jQuery's .click(function) method adds the function to a queue that is executed on the click event~
So actually pulling out a reference to the given function would probably be hairy-er than you expect.
As noted by others, it would be better to pass in a reference to the function; and then you already have the reference you need.
var clicky = function () { /* do stuff */ };
$('#id').click(clicky);
// Do other stuff with clicky
Update
If you really really need to get it out, try this:
jQuery._data(document.getElementById('id')).events.click[0].handler
Depending on your version of jQuery that may or may not work~ Try playing around with
jQuery._data(document.getElementById('id'))
and see what you get.
Got the idea from this section of the source:
https://github.com/jquery/jquery/blob/master/src/event.js#LC36
if you dont know the name of the function you can use
args.callee
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
function clickHandle(e){
if($(e.target) == $('#id')) {
$(newTarget).bind('click', clickHandle);
}
}
$('#id').bind('click',clickHandle);
I think this would be the most symantic way of going about it
Related
Hi I am currently trying to call a function that is saved to a variable, but also has an event handler on it.
col.onclick = function(e){
}
I have not been able to find how to call this kind of set up, and was wondering if it's possible at all, and if it can be done without using jquery.
Help would be nice, thanks in advance.
http://pastebin.com/JJYQeZDG //Code that is the root of the problem.
This code is for a game of checkers, for context.
Simply use () like any other function.
Based on your comments, it looks like you may also have a scoping issue.
I would recommend refactoring your code so your onclick function can be accessed without needed the col object:
var onclick = function(e) {
// note: you will only have "e" if this is invoked as an event callback
};
// later when defining col
col.onclick = onclick;
// ...and later when you want to directly invoke onclick
onclick();
I am trying to display a div on click. The function that is supposed to make the magic happen is:
$(document).ready(function showGogoasa() {
$('.gogoasa-newsletter').show();
});
Unfortunately, it does nothing. Which makes me scratch my head for hours as I have done small things like this in the past and they worked. I am trying to make this modification on the website of a client.
When I check the firebug console it says the following: ReferenceError: showGogoasa is not defined
I tried looking on Google for this kind of error but the similar cases had this kind of issue for not declaring a variable. Well, I do not have any variables.
I am trying to display a div on click.
Your code is running the function on a ready event and doesn't give the error you describe.
Presumably (it would have helped if you had provided a complete test case) you are also trying to bind the function as a click handler, but you can't do that because you have defined it using a function expression and not a function declaration (so it doesn't create a variable called showGogoasa outside of its own scope).
Define the function separately, then assign call it and bind it as a click event handler on the ready event.
$(document).ready(function ready_handler() {
function showGogoasa() { // Define it as a variable in the current scope
$('.gogoasa-newsletter').show();
}
showGogoasa(); // call it now
$("button").on("click", showGogoasa); // call it then
});
Well, I do not have any variables.
That's the problem :)
Functions are first class objects and when you say showGogoasa() that means "Get the value of showGogoasa and call it as a function".
Using jsfiddle or providing more code would have been helpful.
One issue is that you are missing the click event handler. For example when the user clicks on X then Y should happen/show. The following simple example may help you to see how it works:
http://jsfiddle.net/fionaredmond/1vbagj12/
$(document).ready(function(){
$("#showGogoasa").click(function(){
$(".gogoasa-newsletter").show();
});
});
$(document).ready(function() {
$('#idOfYourClickerElement').on('click', function(){
$('.gogoasa-newsletter').show();
});
});
I'm working on replacing an Ext.data.Store load event handler.
The variable me is different every time within the code block but me.store is the same (obtained via StoreManager.lookup). I want the store event listener to update the various me references. Best way i could find was to add another listener (and delete the old one since i don't need it anymore)
I haven't been able to use un / removeListener i.e. it had not effect.
I've found that i could replace the it by accesing the me.store.events and popping the listener from the load event. However this feels hacky and it might make the code dependant on a specific ExtJS version (4.2) since i don't know if it's a private property or not.
Also me.store.hasListeners['load'] doesn't get notified so it only helps because it removes the actual listener but not in the intended manner. The docs don't mention it, but i'm wondering if it may be an inherited property which can be accessed freely.
Are there any alterntives to the working approach i've come to? Can i remove all event handlers for an event without having a reference to the handler? Or is there a simpler approach i'm missing?
var me = this; // an enriched Ext.form.FormPanel, different every time code runs
me.store //obtained via StoreManger.lookup - so the same every time
me.storeLoaded = function (store, records,successful, opts) {
// some code to select a record from records and use it
me.loadRecord(record);
}
};
if (!me.store.hasListener('load')) {
me.store.on('load', me.storeLoaded);
} else{
//tried this, but it doesn't remove it, probably because me.storeLoaded is different each time (parentForm is different)
me.store.un('load', me.storeLoaded);
//this feels hacky, i couldn't find out if events is a private property
if (me.store.events && me.store.events['load']){
me.store.events['load'].listeners.pop()
}
me.store.on('load', me.storeLoaded);
}
The easiest way to implement adding/removing listeners is using the destroyable parameter as described in the addListener function. That way, you can always be sure which one is removed.
Example:
setActive:function(cmp) {
cmp.myActiveListeners = cmp.eventStore.on({
destroyable: true,
load:cmp.refreshStores,
filterchange:cmp.refreshStores,
scope:cmp
});
},
setInactive:function(cmp) {
Ext.destroy(cmp.myActiveListeners);
},
I cannot recommend to blindly remove ALL listeners, since they may be added by other components (e.g. combobox) that you add later. To track down these bugs will grow you quite some gray hairs.
I was able to find an answer in this article ExtJS overwrite listener:
Sometimes you need to overwrite an event listener in ExtJS. Usually
listeners are registered like this myStore.on('load',
this.myFunction, this); then to remove our previously registered
listener, all we have to do is call un (which is an alias for
removeListener): myStore.un('load', this.myFunction, this);
But, what happens when you don't know what function is registered?
Sometimes you will not have a reference to the original function that
was registered. This situation may arise if there is code that exists
in a different flow or may even come as a package! If that is true,
the you may not be able to get a reference to the javascript function
or edit the existing code. In this case, we will have to look at all
of the functions that are registered for this event. We can then
remove the listeners just for a certain event by calling
clearListeners.
clearListeners was the method i was looking for.
It would seem he uses the events property so i assume it is a valid use. It could be translated in my case to:
me.store.events.load.clearListeners()
However since i will only be using the load event on this particular store, i will simply call on them all.
me.store.clearListeners()
Thanks to Alexander, by suggesting not to remove all listeners that actually helped me find the article. However i will stil go with his solution, even if it polutes the store object because i like it better than clearing all listeners on a store, even if only for a specific event.
I need to call "MyOtherFunction" when "MyFunction"(which creates an element) completes, without MyFunction knowing what MyOtherFunction is.
The reason I need this is for extension of a jquery powered fileupload User Control that is used in several places with different functionality. A specific page shows a header and file count for it, and when the upload completes, I need to modify the file count according to how many files are displayed(by created elements) I thought :
$(UserControl).on(MyFunction, UploadElem, MyOtherFunction);
but this route is not accomplishing anything. The most I can alter the User Control is add in a function call, but without effecting the original user control functionality.
I'm not sure if because MyFunction isn't an event and doesn't bubble up or if it just isn't possible to use a defined function as a parameter of .on() is the reason I cannot get this code to work. Any suggestions?
Easiest way I can think of, is duck punching respectively hooking that method:
var _oldMyFunction = MyFunction;
MyFunction = function() {
_oldMyFunction.apply( this, arguments );
MyOtherFunction();
};
I managed to solve my own issue, but the context is important for the answer:
// Using a Global JavaScript object I created:
GlobalNameSpace.ExtensionFunction = function(oParam1, oParam2, oParam3)
{
/// <summary>All parameters are optional</summary>
return; // For instances when it is not being overwritten, simply return
}
//In the Code for the user control:
GlobalNameSpace.UploadControl.UploadComplete(oSender, oArgs)
{
///<summary>Handles the Upload process</summary>
// process the upload
GlobalNameSpace.ExtensionFunction(oSender, oArgs);
}
//and finally in the code to extend the functionality
GlobalNameSpace.Page.Init
{
///<summary>Initializes the page</summary>
// redefine the extension function
GlobalNameSpace.ExtensionFunction = function(oSender, oArgs)
{
GlobalNameSpace.Page.Function(oSender, oArgs);
}
}
This allows me to extend anything I need it to without polluting my objects, and having something generic already existing to call on to make my changes. This solution solves my problem of needing a onCreate function for the elements I create to represent my uploaded items to trigger the header displaying the number of files. Very useful
I was looking over some code a few minutes ago and this confuses me.
$("nav a").mouseenter(function() {
audio.play();
});
I know '$' is jQuery for document.getElementById(""); and mouseEnter is an event handler for 'nav a' but how is the function assigned to the event? It doesn't have any assignment operator '='?
I don't know to much about jQuery right now as I'm trying to completely get JavaScript down. So when I went to modify the code to be pure JavaScript it doesn't seem to work...
document.getElementById("playAudio").onclick(function () {
audio.play();
});
I don't understand why? I figured it was the same code?...
mouseenter is a function. Similar to:
var element = {elm: document.getElementById('test')};
element.mouseenter = function(func) {
element['elm'].addEventListener('mouseenter', func);
};
element.mouseenter(function() {});
The function is passed, and the function is anonymous (doesn't have a name).
You could also do:
function foo() { audio.play(); }
$('nav a').mouseenter(foo);
The dollar symbol is not just limited to getElementById(), it the the jQuery object and in your case, is calling the nav element then grabbing the a tags within the nav. After grabbing the element(s), it then attaches the event anonymously, allowing the function to run whenever the event is fired.
You're passing a function object (created with a function expression) to jQuery.mouseenter, and jQuery takes it from there.
FYI, part of what you're trying to get down here is the Document Object Model (DOM). You're trying to make the code pure JavaScript + DOM API. It's good to learn the fundamentals of both JS and the DOM, but be aware that jQuery smoothes out many inconsistencies in browsers' implementations of the DOM, such as registering event listeners.