Function inside event listener [duplicate] - javascript

This question already has answers here:
"this" keyword in event methods when using JavaScript prototype object
(4 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
If a function inside an event listener is called, say for instance, window.load, are all other functions inside said function expected to be ran on load as well? I have an issue with a function being called on window load and that function calling another function. At the last step I want to add an event listener to watch for form submission. However the listener function has no access to the the variables called from the original load listener function.
var Handler = {
ajaxURL: null,
domIDs : null,
httpRequest : null,
init: function(config) {
this.httpRequest = {};
this.initConfig(config);
this.setLoadHandler();
},
initialize: function() {
this.initializeDocumentNodes();
},
setLoadHandler: function(){
var self = this;
this.addEvent(window,'load', function() {
self.initialize();
});
},
initializeDocumentNodes: function() {
this.dom = {};
for(var key in this.domIDs) {
this.dom[key] = document.getElementById(this.domIDs[key]);
}
this.dom['loginForm'].addEventListener("submit", function(ev) {
ev.preventDefault();
console.log(this.dom['userNameLoginInput']);
console.log(this.dom['passwordLoginInput']);
});
},
this.dom is undefined inside the form submit listener.
this.dom['loginForm'].addEventListener("submit", function(ev) {
ev.preventDefault();
console.log(this.dom['userNameLoginInput']);
console.log(this.dom['passwordLoginInput']);
});
Could someone please help me to understand this? Thank you so much.

Related

How to get "this" object in to a callback function? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
How do I get this into a callback?
Started out with this, worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
});
this.reload();
},
});
Then to only call reload if the request worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
this.reload();
});
},
});
Of course "this" is no longer references the object I want to access.
Or how would I gain access the parent object?
You may just bind your this inside the callback.
Note: Beware of any side-effects. Apparently you don't seem to need the new this inside the callback.
Try:
$('#grid').w2grid({
name: 'grid',
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], (function(data) {
this.reload();
}).bind(this));
}
});
When arrow-functions are available, I'd suggest to use them rather than binding this.
You can do it like this:
let parent = this;
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
parent.reload();
});

nested function calls on "click" event in javascript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
here is my code, Now some people may say why not just include the one line code in that function block but i don't want to, how do i achieve that. How can i call this.click method on "click" event of the button
var i = 0;
function el() {
this.type = "button",
this.el = false,
this.click = function () {
this.setHtml(i++);
},
this.setHtml = function (t) {
this.el.innerHTML = t;
}
fragment = document.createDocumentFragment(),
element = fragment.appendChild(document.createElement(this.type));
element.setAttribute("data-el", this.type);
element.innerHTML = "Default Button";
this.el = element;
attachEvent("click", this);
}
// this should be a seperate function ....
function attachEvent(ev, me){
//me doesn't work, but i want it to call the click method
me.el.addEventListener("click", me.click, false);//....
}
div = new el();
document.getElementById('areaA').appendChild(div.el);
Change this:
me.el.addEventListener("click", me.click, false);//....
to this:
me.el.addEventListener("click", me.click.bind(me), false);//....
When you pass only me.click, you are just passing a reference to the click function and the binding to me is lost. .bind() will create a self-binding stub function that will give you the right this value when the event handler is called.

remove event listener on a input in pure javascript [duplicate]

This question already has answers here:
How to removeEventListener that is addEventListener with anonymous function?
(5 answers)
Closed 6 years ago.
I an attaching event listeners in input box by using ID. so its working fine but I want to remove event listeners its will not work for me.
document.getElementById("myInput").addEventListener("keyup", function({
console.log(document.getElementById("myInput").value);
});
document.getElementById("myInput").removeEventListener("keyup",function() {
});
The second argument needs to be the event listener you want to remove (so you need to keep a reference to that function around instead of putting a function expression directly as the argument to addEventListener).
You're passing it a brand new function. It doesn't get removed, because that function wasn't listening in the first place.
var in = document.getElementById("myInput");
function myListener (event) {
console.log(in.value);
}
in.addEventListener("keyup", myListener);
in.removeEventListener("keyup", myListener);
Try that
var fn = function({
console.log(document.getElementById("myInput").value);
}
document.getElementById("myInput").addEventListener("keyup", fn);
document.getElementById("myInput").removeEventListener("keyup", fn);
var body =
document.querySelector('body'),
clickTarget =
document.getElementById('click-target'),
mouseOverTarget =
document.getElementById('mouse-over-target'),
toggle = false;
function makeBackgroundYellow() {
'use strict';
if (toggle) {
body.style.backgroundColor = 'white';
} else {
body.style.backgroundColor = 'yellow';
}
toggle = !toggle;
}
clickTarget.addEventListener('click',
makeBackgroundYellow,
false
);
mouseOverTarget.addEventListener('mouseover', function () {
'use strict';
clickTarget.removeEventListener('click',
makeBackgroundYellow,
false
);
});
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);
the second argument is the eventlistener you want to remove, see this

JS: Access from a property to another property in the same object [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I'll explain my issue using an example:
I have an object which is called 'ExampleObj' which returns 3 property 'init', 'age', 'weight' and I need to access from age to weight but for some reason i can't do that. Could you explain me why and how can I achieve the correct result?
EDIT: this is the current code, self.tabAnimation() is working on dom ready but... is not working on "click", even if I use (); check the **** in the code, is the line which triggers me error.
return {
init: function() {
var self = this;
tabs.init();
self.tabAnimation();
tabToggler.on('click', self.tabAnimation );
},
tabAnimation: function() {
var self = this;
var activeTabBars = function() {
console.log('lol');
tabItem.find(bars).each(function() {
var me = this;
****self.animateBars(me,1000)****
});
}
animateOnVisible.init(tabItem, activeTabBars);
},
animateBars : function(el, duration) {
var percentage = $(el).data('value') + "%";
$(el).animate({
'width': percentage
}, duration);
}
}
}
Thank you very much
Davide
You have to use this:
age: function() {
console.log('some random log');
var me = this;
me.weight;
me.weight(something);
},
You don't have to assign this to another variable, but it doesn't hurt anything if you do.
Note that in your "init" function,
self.age;
by itself will do nothing. To call the function, you have to write it
self.age();

Removing child-function event listeners

In building an extended input field (a complex date picker), I need to use two key event listeners. One is attached to the input field, and launches the interface. This is easy.
The second is attached to document, in order to close the complex overlay. Click on the overlay, and it does nothing. Click outside: the overlay disappears and the input field's value is updated.
It also needs to remove the event listener from the document.
This would all be straightforward… if it weren't based on object structures. I am not calling a stand-alone function. I am calling a child function of the data object associated with the field (which the field then has no way of referencing back to).
__DateField.prototype.activate = function () {
…
var t = this;
window.setTimeout(function () { document.addEventListener("click", function (ev) { t.closeDateSelector(ev) }, false); }, 0);
…
}
(I haven't figured out why that event attachment needs to be nested within the setTimeout, but if I don''t do it that way, it calls itself immediately.)
Anyhow, the problem is then that I cannot successfully call document.removeEventListener() because I it's not the same initial function.
Also, I can't approach it by attaching the function as a stand-alone, because I need the reference to the related __DateField object.
How can I remove that function from document?
I have looked at the various threads that say there is no way to inspect event listeners added via 'addEventListener`, though wonder if they may be out of date, as Firebug can list them…
To remove it, you must have a reference to the function, so the question boils down to: How can I keep a reference to the function?
The simplest answer, since you already have an object handy, is a property on the object, if you can rely on this being correct as of when you do the removal:
__DateField.prototype.activate = function () {
// …
var t = this;
window.setTimeout(function () {
t.listener = function (ev) {
t.closeDateSelector(ev)
};
document.addEventListener("click", listener, false);
}, 0);
// …
};
// To remove
__DateField.prototype.deactivate = function() {
if (this.listener != null) {
document.removeEventListener("click", this.listener, false);
this.listener = null;
}
};
Or if that's a problem for some reason, you could use a variable in a scoping function:
(function() {
var listener = null;
__DateField.prototype.activate = function () {
// …
var t = this;
window.setTimeout(function () {
listener = function (ev) {
t.closeDateSelector(ev)
};
document.addEventListener("click", listener, false);
}, 0);
// …
};
// Later, when removing
function removeIt() {
if (listener != null) {
document.removeEventListener("click", listener, false);
listener = null;
}
}
})();

Categories

Resources