Cannot update global variable within addeventListener function - html

Basically when running addEventListener I cannot access any of my saved variables from outside the function I am creating.
In the following code I always get the error Property 'xAxisLabel' does not exist on type 'HTMLElement'.
xAxisLabel:string = 'xAxis';
xAxisField:HTMLElement;
filterChanged(element: HTMLElement) {
element.addEventListener("change", function(){
this.xAxisLabel = 'Countries';
});
}
ngOnInit() {
this.xAxisField=document.getElementById('xAxisField');
this.filterChanged(this.xAxisField);
}
I am sure it's a fairly simple solution but I haven't been able to find it online. Any help would be appreciated.

It is due to 'this' keyword binding. You need to change your code to use arrow function, so:
filterChanged(element: HTMLElement) {
element.addEventListener("change", () => {
this.xAxisLabel = 'Countries';
});
}
now this.xAxisLabel refers to correct value

Related

pass a local variable to an click function

I want to pass a local variable from one function to another and I have tried some solutions but they didn't work because I have a click function, I need to put the variable first of all and I don't how to do it, also I declared the variable outside the function but if I use it outside of all the functions it doesn't has all its values or inside the function resaltar nothing appears, any help is welcome
let children=$('div[class^="fila"], div[class^="pieceRow"]' ).children()
var clase
$(children).each(function getClass(){
clase=$(this).attr('class')
$(clase).on('click', function resaltar(){
if (clase==clase) {
$(this).addClass('shadow')
}
})
})
this is the html code https://jsfiddle.net/qb5fwcus/
Please try this code :
let children = $('div[class^="fila"], div[class^="pieceRow"]' ).children();
$(children).on('click', function(){
var clase = $(this).attr('class');
resaltar(clase);
})
function resaltar(clase){
$('.shadow').removeClass('shadow');
$('.' + clase).addClass('shadow');
}
Explanation : You can not pass any value for the callback function for any event handler. Either it can be an anonymous function, or a function, not requiring any argument. However, you can achieve that, by making the callback function anonymous, and call any function from it. In this way, you can pass variables.
PS : Let me know if I got it wrong in any manner :)
Let's assume that you will be passing it to a pure JS function.
function myFunc() {
console.log("My function!");
}
In your 'click', you're calling the function ''resalter'', that you're also defining on the spot.
You want to call myFunc, so:
$(clase).on('click', myFunc())
Now, myFunc is not expecting a variable. Let's just pass a variable:
function myFunc(myVar) {
console.log("Passing a variable of type: " + typeof myVar);
}
Now, you're only expected to pass this var in the function you're calling. Given the previous example I gave, we have:
let x = 1; // our variable
$(clase).on('click', myFunc(x))
This way you're passing 'x' as a variable, of type integer. Use this code as inspiration to try and reach your goal. It is a bit hard to give a more exact answer, given that we don't know what variables have to be passed to what function and what the purpose is.
Good luck!

React Native ArrowFunction Against normal function (Appstate)

I am trying to find out the difference between 2 functions. In my
react native app I use an AppState eventlistener to check if the app
is running in the background or foreground (see code below):
AppState.addEventListener('change', this._handleAppStateChange);
the function looks like this:
_handleAppStateChange = (nextAppState) => {
console.log('nextAppState', nextAppState)
this.setState({
appState: nextAppState
});
};
I did not like the way te function is made because in the listener you call it without a parameter
but it the function itself it has a parameter. So I wanted to change this to make it more clear.
This is what is made:
_handleAppStateChange (nextAppState) {
console.log('nextAppState', nextAppState)
this.setState({
appState: nextAppState
});
};
This works fine the nextAppState is still logged but the setstate does not work anymore
is says that it`s not a function. Can someone explain me why?
And can someone explain me which of both functions is the best to use.
Thx a lot!
Start using arrow functions, one of the reason why arrow functions were created is for the problem you have mentioned i.e losing this in the function context.
So in order for your function to work you need to bind the function to this.
In your constructor add this line
this._handleAppStateChange = this._handleAppStateChange.bind(this)
Or you can replace this function
AppState.addEventListener('change', this._handleAppStateChange);
to
AppState.addEventListener('change', (nextAppState) => this._handleAppStateChange(nextAppState));
Bonus.
If you need to pass extra parameter other than nextAppState or which is in state. This line wont work
AppState.addEventListener('change', (nextAppState, this.state.someRandmValue) => this._handleAppStateChange(nextAppState, this.state.someRandmValue));
As this.state.someRandomValue is undefined since handleAppState wont emit this value instead use this
AppState.addEventListener('change', (nextAppState) => this._handleAppStateChange(nextAppState, this.state.someRandmValue));

React upgrade: "this" visibility in getDefaultProps

I am upgrading some older react component I inherited (v0.10.0) to work with the latest version of react (v0.14.8).
The following scenario stopped working:
// within a react component
onClick: function() {
// DO SOMETHING
}
getDefaultProps: function () {
return {
someProp: 'prop',
onClick: this.onClick
}
}
This is easily resolved moving the code into an anonymous function, like the following:
getDefaultProps: function () {
return {
someProp: 'prop',
onClick: function() {
//DO SOMETHING
}
}
}
My question is: why has the visibility of 'this' changed at that level and what's the best way to refactor this code? And what if I had-to/wanted-to use 'this' at that level?
Any help appreciated, as a disclaimer I am a react super-beginner!
The result of getDefaultProps() is shared across all instances of a component. That means that the result can't rely on any particular instance of the component. The reason it changed is likely because of the performance benefit from caching, although I can't say for sure.
As for refactoring the code, I'm not sure there's a silver-bullet here. From my perspective what you currently have seems like an anti-pattern. Props are meant to be passed in by consumers that have no knowledge of the inner workings of the component, so it seems odd that a default value for a prop would depend on the inner workings. Without knowing exactly what you're doing, I would say your best bet is to just use null as the default value for the prop, then check the value at runtime when you do have access to the this context.
handleSomeAction() {
if (!this.props.onClick) {
// DO SOMETHING
}
}

Passing a function as an attribute value

I was wondering if it was possible to pass a function foo() as an attribute func="foo()" and have it called this.func() inside of the polymer element?
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: Object,
},
ready: function() {
this.func();
}
});
I've been trying to get this working for ages with no luck.
Thanks in advance.
<foo-bar func="foo()"></foo-bar>
Polymer({
is: 'foo-bar',
properties: {
func: {
type: String, // the function call is passed in as a string
notify: true
},
attached: function() {
if (this.func) {
this.callFunc = new Function('return '+ this.func);
this.callFunc(); // can now be called here or elsewhere in the Polymer object
}
});
So the trick is that "foo( )" is a string when you first pass it to the Polymer element. I fought with this for a while as well and this is the only way I could find to get it done. This solution creates a function that returns your function call, which you assign as the value of one of your polymer element properties.
Some people might say you shouldn't use the Function constructor because it is similar to eval( ) and.... well you know, the whole 'eval is evil' thing. But if you're just using it to return a call to another function and you understand the scope implications then I think this could be an appropriate use-case. If I'm wrong I'm sure someone will let us know!
Here's a link to a nice SO answer about the differences between eval( ) and the Function constructor in case it can help: https://stackoverflow.com/a/4599946/2629361
Lastly, I put this in the 'attached' lifecycle event to be on the safe side because it occurs later than 'ready'. I'm not sure if an earlier lifecycle event or 'ready' could be used instead of 'attached'. Perhaps someone can improve this answer and let us know.

Calling function inside angular directive and inject event in parameters

I need your help.
I have a directive with a function parameter ( scope: { myParam: '#'}). And I'm passing the parameters in HTML, like my-param="myFunc(param1, param2)"
This works perfectly. But, I need to inject the event object in to the parameters. Does some one know how can I do that?
I tried $provider.annotate and $provider.instantiate, but they did not work because it's taking the reference function in directive. ($a in my case), so it can't get the function arguments.
any idea?
When you're calling a function created by the & isolate scope syntax, you can pass parameters to it as a named map. If your directive is defined like this:
scope: { myParam: '&' },
link: function (scope, el) {
el.on('click', function (e) {
scope.myParam({$event: e});
});
}
and used like this:
<my-directive my-param="console.log($event)"></my-directive>
... you should see the desired behavior.
chrisrhoden's answer is great. I would suggest to expand upon it a bit with the following. Doing so will help prevent ng-click double-firing issues relating to mobile devices and/or AngularJS conflicts with jQuery.
myApp.directive('responsiveClick', function(){
return {
scope: { myCb: '&' },
link: function (scope, el,attr) {
el.bind('touchstart click', function (e) {
e.preventDefault();
e.stopPropagation();
scope.myCb({$event: e});
});
}
}
});
along with the markup as follows:
<a class="mdi-navigation-cancel" my-cb="removeBasketItem($event,item)" responsive-click></a>
have you tried passing it in the original function?
my-param="myFunc($event, param1, param2)"