This question already has answers here:
Use arrow function in vue computed does not work
(6 answers)
Closed 5 years ago.
I am using a lambda expression within the methods section of a Vuejs component.
The example is below
I trigger alertyou() and get the alert, click okay. Then in the vue developer tools I see this.activated becomes true.
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
activated: false
}
},
methods: {
alertme: () => { alert('Clicked'); this.activated = false; },
alertyou() {
alert('Alert You');
this.activated = true
}
}
}
However, when I click the button that triggers the alertme lambda. I get the alert message, click okay. But then this.activated stays true!
What is going on here is this a limitation with lambdas? Can you only trigger one statement per lambda? Or does this have to deal with scope once an alert is fired?
What is going on here is this a limitation with lambdas? Can you only trigger one statement per lambda? Or does this have to deal with scope once an alert is fired?
It’s neither.
An arrow function keeps this bound to the context it was when the arrow function was created. In this case, this is not the vue instance. It’s probably window
A function declared on an object using the function keyword (or the ES6 object shorthand style) will normally have this bound to the object on which the function is declared.
That’s why you can access this.activated on alertyou but not alertme
You’ll want to use the same syntax as alertyouto declare the alertme method.
Change alertme: () => { alert('Clicked'); this.activated = false; } to alertme() { alert('Clicked'); this.activated = false; }. You can see a working example here
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
I know this may seems silly but I'm a beginner and I just need to make sure that I understand it well:
In JavaScript when I define an event listener, the callback function is called without () to prevent immediate execution, like the below example:
document.querySelector('#button').addEventListener('click',eventHandler)
function eventHandler() {
alert('clicked')}
my confusion is if implemented the above in a class and defined the eventHandler callback function as a method, I have to use () when I call it, like the below example:
class home {
constructor(){
this.button = document.querySelector('#button')
this.clickEvent()
}
//events
clickEvent(){
//here i have to use eventHandler() not eventHandler
this.button.addEventListener('click',()=>this.eventHandler())
}
//method
eventHandler(){
alert('clicked')
}
}
new home()
In code snippet with class, you are passing a function to addEventListener function which then calls the eventHandler function.
() => this.eventHandler() is an arrow function which executes this.eventHandler() inside its body
if you remove the arrow function then you will have to pass the name of the function instead of calling it
this.button.addEventListener('click', this.eventHandler)
Edit:
keep in mind that if the eventHandler method uses this, then you may run into problems because of how value of this is set in different cases.
Currently, eventHandler function isn't using this but you should read how to access correct this inside callbacks.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
Recently, I've come across this problem where I had two methods in a class. One was referring to another but the other wasn't being recognized even though I could execute them individually.
class ButtonProcessor {
buttonClick() {
this.otherMethod();
}
otherMethod() {
console.log("This does not work!");
}
}
var buttonProcessor = ButtonProcessor;
document.getElementById("button").onclick = buttonProcessor.buttonClick;
The first method was called from a button click which was associated with a callback to that method.
One solution I found for this is to make the method that is called by the button a seperate function from the class and make it reference a class object that was already being used else-where. This is because apparently, when a method is referenced in a callback, using this to refer to another method doesn't work, because the callback only considers that one method.
class ButtonProcessor {
otherMethod() {
console.log("This does work!");
}
}
var buttonProcessor = ButtonProcessor;
function buttonClick() {
buttonProcessor.otherMethod();
}
document.getElementById("button").onclick = buttonProcessor.buttonClick;
Could there be another way to fix this?
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I've created a class and I'm trying to call a method from inside that class from another method inside that same class. I've seen online that some people say use 'this' keyword, but as you can see from the example, that doesn't work. Can someone please explain in simple terms how to call a class method from inside another method in that same class? Thanks!
class Form {
constructor() {
}
fn1 () {
console.log('fn1 calling fn2 now:')
this.fn2();
}
fn2 () {
console.log('fn1 called me')
}
}
let myForm = new Form();
myForm.fn1();
Example can be found here
The error I keep getting is this: Uncaught TypeError: this.fn2 is not a function
There's nothing wrong with the code you show embedded into your question - that should work just fine. The issue arises when you pass a method to .addEventListener() as a callback (which shows in the code you have a link to).
Change this:
document.getElementById('call-func').addEventListener('click', this.fn1);
to this:
document.getElementById('call-func').addEventListener('click', this.fn1.bind(this));
The problem is that passing this.fn1 loses the value of this so when the listener calls the callback later, the object that it belongs to is lost and then this inside of fn1() is wrong. In addition, .addEventListener() explicitly sets the this value to the DOM element that triggered the event (which is not your object).
The same thing would happen if you did this:
let f = this.fn1;
f();
Using .bind(this) rebinds the value of this when the listener calls it.
FYI, you could also do it this way with a fat-arrow function:
document.getElementById('call-func').addEventListener('click', () => this.fn1());
Or, an older way of doing it:
var self = this;
document.getElementById('call-func').addEventListener('click', function() {
self.fn1();
});
My preference is to use .bind(this).
More explanation on event listeners and this here: "This" within es6 class method
More explanation on the general concept of how this gets set when a function is called here: When you pass 'this' as an argument
This question already has answers here:
onClick handler is triggered on each render cycle
(4 answers)
Closed 4 years ago.
Could someone please explain to me why when i am trying to bind onClick action to element it works good until i dont add brackets to pass arguments to function?
getUser(id) {
console.log(id);
}
renderResults(){
if (typeof this.props.results[0] == 'undefined') {
return null;
} else {
var results = this.props.results[0].payload;
var formatedResults = results.map((singleResult) => {
return (
<div className="col-md-4 single-result" key={singleResult.account_id} onClick={this.getUser(singleResult.id)}>
<div>{singleResult.nickname}</div>
</div>
)
});
return formatedResults;
}
}
that code works on load instead of on click and returns x console logs just when page is loaded not when i click element, but when i remove brackets and i am console logging static text in getUser function it works good.
Any help or helpful links? Thanks
onClick={(e) => this.getUser(singleResult.id)}
doc : https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
We have different ways to bind events to your DOM elements in react.
One of the most commonly used way is using 'bind'
Another is using arrow functions.
Using public class fields syntax
In your scenario, you are calling your function directly by doing this.getUser(singleResult.id). This executes the method rather than binding it to your DOM element.
Try changing it to this.getUser.bind(this, singleResult.id) which should be passing your singleResult.id to your method.
Another way to do it is using arrow functions like onClick={(e) => this.getUser(singleResult.id)}
But be careful while using arrow functions because there are chances of unnecessary rendering of components in some scenarios.
Please make sure to take a look at the documentation to give more details on events handing in react
use constructor to bind the function. use inside your component. and all your codes as it is
constructor(props) {
this.getUser = this.getUser.bind(this);
}
It's because you're calling the function, instead of passing it to onclick.
You can bind the value to the function, with an arrow function, if you're not passing anything, then it will keep its state:
getUser = () => {
console.log(this);
}
onClick={this.getUser}
or in your case pass the function to the onclick:
onClick={(e) => this.getUser(singleResult.id)}
You can read all about it here
This question already has answers here:
JQuery callback to previously defined function
(3 answers)
Closed 7 years ago.
I'm having issues with writing some of my first JQuery code. I'm experimenting with some Codecademy stuff, just messing around and seeing how it works. Right now I'm pretty confused about an issue with anonymous functions: calling a function anonymously works but naming the function and calling it by name does not. The code is supposed to, on clicking an icon, open a menu from the left side of the screen and shift the rest of the page to the right; then do the reverse on clicking the close icon. The first code block works perfectly, the second just opens and closes the menu immediately after the page loads and then does nothing. Is there something I'm missing about order of operations in JS/JQuery or what?
Anonymous:
function main() {
$('.icon-menu').click(function() {
$('.menu').animate({left:'0px'}, 200);
$('body').animate({left:'285px'}, 200);
});
$('.icon-close').click(function() {
$('.menu').animate({left:'-285px'}, 200);
$('body').animate({left:'0px'}, 200);
});
}
Named:
function main() {
$('.icon-menu').click(open());
$('.icon-close').click(close());
}
function open() {
$('.menu').animate({left:'0px'}, 200);
$('body').animate({left:'285px'}, 200);
}
function close() {
$('.menu').animate({left:'-285px'}, 200);
$('body').animate({left:'0px'}, 200);
}
Thanks to anybody who can enlighten me.
You have
$('.icon-menu').click(open());
() calls a function.
You are calling open immediately and then passing its return value (undefined) to click.
Remove the () and pass the function instead.
Remove the parentheses. open() and close() call the functions, but you just want to pass a reference to the function.
function main() {
$('.icon-menu').click(open);
$('.icon-close').click(close);
}
Remove the brackets after function within clickhandler, because you are executing them emediatly with this syntax.