Retrieve and modify a previously assigned event function? - javascript

Can I retrieve and modify a previously assigned event function?
For example I originally add an onclick event handler to a node, like this :
var someNode = document.getElementByID('someNode');
someNode.onclick = function(){
//some stuff
};
Ideally later I would need to get back this event and modify the "some stuff" code content.
Is it doable in javascript?

You can modify the onclick event. Simply assign that to a new function will do. However, similar to most dynamic languages, function is not a data structure that you can easily modify. So keeping the same function but modifying it is AFAIK impossible.
The way I would suggest is to create a new function for your use, and assign it to the onclick property. However, JS is a very nice language that provide closure to your variables. So you can make a function that return a function to fit your need if you need some flexibility.

It's not really clear what you are trying to accomplish. But do you mean something like that ?
var someNode = document.getElementByID('someNode');
let customizablePart = function (e) {
// do some stuff
}
someNode.onclick = function (e) {
// unchangeable instructions
customizablePart.call(this, e)
}
// later ...
customizablePart = function (e) {
// do new stuff
}

Related

Detect when a function is getting called in JavaScript

There are several elements on HTML page which triggers a js function HardCoded().
I cannot modify HardCoded() function.
I want to run some custom js code after the HardCoded() function is getting called. How can I do that? Is there any handlers for js functions?
I'm building a chrome extension that's why I cannot modify page source code.
I have access to JQuery.
One way is to find all elements who are calling HardCoded() and attach events to those elements but I would like to avoid this method.
You could do something like this:
var oldFn = HardCoded;
window.HardCoded = function(){
var res = oldFn.apply(this, arguments);
// New Code ....
return res;
}
What this does is to create a reference to the HardCoded function, redefine this function and then call the old implementation using the previously created reference.

Events in Object variables

Can you place a jQuery event inside of an object variable like so:
var taskObj = {
buttonClick:function() {
$("#button").click(function() {
alert("Something");
)};
}
}
If so how would you call it the method? Could I possibly bind it to an event? Reason I'm asking is because I'm trying to change some spaghetti code (alot) and make it a bit easier to maintain without having to rewrite it all. Any insight would be much appreciated.
Yes, you can do that. Your current object only has a click handler, so to actually bind it just run:
taskObj.buttonClick();
On DOM ready. To have an object hold the functions for handlers, you could do:
var taskObj = {
buttonClick:function() {
alert("Something");
}
}
And define the handler as:
$("#button").click(taskObj.buttonClick);

Cache a variable exclusively on a function

Is there a way to cache a global variable for a function within a group of functions, without calling that function directly from another?
For example, if I have a group of functions wrapped in a parent function like this:
function parentFunction() {
var myVariable;
someDiv.addEventListener('click', function (e) {
myVariable = e.target;
});
anotherDiv.addEventListener('click', function (e) {
// use myVariable without it changing when the above is fired again.
});
}
The global variable is declared at the start, it is given a value in the first function, which carries over to the second for use.
But how can I stop it from continually updating in the second function, if the first function fires again?
Could I add another event-listener inside the second function to check if the first fires again and ensure the variable doesn't change?
You can set the variable only once in the first function:
someDiv.addEventListener('click', function (e) {
if (!clickedLink) {
clickedLink = e.target;
}
});
Or, you can apply any logic you want there. Sometimes, saving state like this in a semi-global for later use in a different event handler is a warning sign that you might have a design issue. If you explain more about what you're really trying to do, we could offer an opinion on whether there's a better way to solve your design issue.
Not sure if I fully understand the question. If you want to have two distinct bindings, you need two variables. Maybe so:
function parentFunction() {
var myVariable, anotherVariable;
someDiv.addEventListener('click', function (e) {
myVariable = e.target;
if (!anotherVariable) {
anotherVariable = e.target;
}
});
anotherDiv.addEventListener('click', function (e) {
// use anotherVariable
});
}

Alter an existing onClick function with Javascript

My query is regarding using Javascript to change the value of an onclick function that already exists on the page.
There's a button. This button has the following onclick function:
onclick="if (confirm('Yahdy Yahdy yah?')) { someFunction(); }; return false;"
I would like to change the onclick function using Javascript to just be as follows and or extract the someFunction(); and run that directly without having to go through the confirmation. As I understand it, you can't confirm a confirm through scripting, so my only option is to run someFunction(); directly. My question is, how do I access someFunction() directly as someFunction() contains randomly generated values each time the page loads.
onclick="someFunction();"
That's basically what I'd like, so I can then call onclick() directly. I'm happy to use vanilla or jQuery to go about this.
TLDR: I want to extract PART of the old onclick function and make a new onclick function with JUST that part.
You can do this:
var code = obj.onclick.toString();
That will give you the javascript code assigned to that click handler to which you can search through it, find what you're looking for and reassign the click handler to something else.
I have no idea if this is the best way to do it, but here's something that worked for me:
function nullConfirm() { return true;};
(function() {
var obj = document.getElementById("test");
var code = obj.onclick.toString();
code = code.replace("confirm(", "nullConfirm(");
var matches = code.match(/\{(.*)\}/);
if (matches) {
obj.onclick = function() {
eval(matches[1]);
}
}
})();

call vs passing object in javascript

ive been using call a bit recently in some tutorials I've been following but am more used to passing the object. I was wondering is it best to use call. What's the most efficient way?
var editor = function(someParam){
//do something with this
}
var testFunction function(someParam){
editor.call(this, someParam);
}
or
var editor = function(obj, someParam){
var self = obj;
}
var testFunction function(someParam){
editor(this, someParam);
}
I would stick with passing the object to the function as long as you can structure the function that way.
I see call more like a utility if the function cannot be changed anymore and you really have to inject a different this context.
Also, consider using the prototype approach if your function is bound very close to some object that you want to call the function on.
Also, call will be less performant than passing the object to the function, as the injection of a different this has some overhead.
In some cases call is very useful, for example when adding event handler:
window.addEventListener('load', function(){
var cb = document.getElementById('myCheckBox');
cb.addEventListener('change', onchange);
onchange.call(cb); // sets `cb` as `this` in `onchange` function
});
function onchange(){
// I'm using 'this' for current element
if(this.checked)
alert('checked');
}
In this case onchange will be called on window load and every time checkbox checked state changes

Categories

Resources