React event target value in onChange - javascript

What is the difference between
onChange={({ target: { value } }) => setInsertedTitle(value)}
and
onChange={setInsertedTitle}
When should one or another be used?

Using onChange={({ target: { value } }) => setInsertedTitle(value)} you are passing the current target value as a parameter.
It is because onChange generates an Event, and you access the value by event.target.value ...
event: {
target: {
value: "string"
}
}
On the other hand, when you use the function like in onChange={setInsertedTitle}, it receives the event.
You can see it here: https://codesandbox.io/s/compassionate-fast-krrib?file=/src/App.js

Look at what each does and spot the differences:
onChange={({ target: { value } }) => setInsertedTitle(value)}
Creates an arrow function (let's call it func)
Whenever onChange/func gets called, e.g. func(event):
It uses destructuring to set value to the value of event.target.value
It calls setInsertedTitle with value (therefore event.target.value)
In the other case:
onChange={setInsertedTitle}
When onChange gets called with event, we directly call setInsertedTitle with event.
Therefore the main difference is whether it passes event.target.value or just event.

The first one passes a function to onChange that, when called, will get the value of the target element of the event (this is probably an input element, so target will be that input element) and pass that value to setInsertedTitle. So when the event occurs, setInsertedTitle gets called with a string (the value of the input).
The second one will directly pass setInsertedTitle to onChange. When the event occurs, setInsertedTitle will get called with an event object rather than the value of the input.
For the avoidance of doubt: The first one is correct, the second one is incorrect. (Even if you wanted to have an event object in your state data — which you almost certainly don't — you can't just keep the one you're passed; you're not allowed to keep them as they get reused [I think that's going to change at some point].)

Related

React handleChange methods event.target.value vs. (event, newValue)?

What is the difference between:
const handleChange = (event) => {
setValue(event.target.value);
};
and
const handleChange = (event, newValue) => {
setValue(newValue);
};
? The first seems to work in some cases, and the second in others.
First of all, I want to tell you that you are just passing a function for events like onChange or onClick, right? So, this is simple. We can pass any parameters to a function based on our needs. For those events, we basically use the following syntaxes:
const handleChange = (event) => {
setValue(event.target.value);
};
Here handle change is just a normal function, so it is not required that you only have to pass event as your parameter. It can be anything that you require to process that function. For the above use case, you needed input value that's why you passed the event object as the first param. But, maybe sometimes you will need extra data to work with that function. For example, you have multiple inputs, like below. You can add such inputs by clicking plus icon. And we might be storing data in an array of objects [{trait_type:'', value:''},{trait_type:'',value:''}], each array element represents a pair of those input. It will be efficient to use a change handler that accepts both (event and index) of input as params.
What is the main point is you are just passing functions to those events, and you can pass 0 or more parameters. It is not the rule that you have to pass Event for all event handlers. Yeah, sometimes you might require an Event object to stop propagating the event. Hope this explanation will help you. Make changes as you needed and best suited for you. Thank you.

How to stop a scheduled ontick event on Cesium

I have two buttons on my code which will add and delete primitives when clicked. On the other hand, I have an event listener for onTick method which will get as an input the active primitive and a variable indicating its index, and is supposed to used that primitive with that particular index for the event.
When I did debugging I saw that although the input argument was updated but the parameter used by the event listener were not updated. And I got the error that the object is destroyed.
Do you know how I can update these arguments or stop the previously scheduled events?
onTick is a Cesium Event with an addEventListener function that returns a hook to unsubscribe. You simply call the return value, later, when you want to end your subscription to that event.
var unsubscribe = viewer.clock.onTick.addEventListener(myCallback);
// ... later ...
// Stop the onTick callback.
unsubscribe();

Computed binding doesn't work with on-click (Polymer)

<template is="dom-repeat" items="{{myItems}}">
<div on-click="{{ComputedBindingFunction(item)}}">Foo</div>
</template>
This yields an error saying:
listener method {{ComputedBindingFunction(item)}} not defined
Shouldn't the function be executed, instead of literally trying to attach the function name with {{}}'s to on-click according to the docs?
Note that ComputedBindingFunction returns a function.
The example shown in the documentation you link to isn't for calling methods or firing events, it's for using computed bindings.
i.e.
<div>{{ComputedBindingFunction(item)}}</div>
If you're your trying to trigger an event, remove the braces:
<div on-click="ComputedBindingFunction"></div>
...
Access item from the triggered event
ComputedBindingFunction: function(event){
_ComputedBindingFunction(event.model.item)
}
Firstly, Attributes for event listeners (e.g., on-click, on-tap, etc) don't allow computed bindings as an argument, only a string.
Secondly, even if they did, which would be super cool in the future, your example still wouldn't work because you are returning a function from the computed binding and not a string.
Your computedFunction should instead be returning the name of the function you want to call which is defined using the arguments supplied when the event is fired.
Example:
html polymer event handler attribute
<div on-click="{{computeFunction(a, b}}">Button</div>
computeFunction makes a new function "add" and returns the name of this function as a string.
computeFunction: function(a, b) {
functionName = "add";
this[functionName] = function() {
// Does whatever you want with arguments, a, b
// Like maybe adding them together.
return a + b
}
return functionName;
}
add: function(a, b) {
return a + b;
}
This way the function called "add" which is called when the on-click event occurs would always be using the new variables "a" and "b" assigned to it.
Until this is available, which it might be never, You can store parameters in an attribute on the element which fires the event.
<div on-click="someFunction" someFunction="{{item}}">Button</div>
someFunction: function(e) {
// Current target is the node that fired the event,
// It has our stored parameter "{{item}}" as a value of "someFunction"
var item = e.currentTarget.getAttribute('someFunction');
// Do something with item
console.log(item);
}
As you can see I stored the item in an attribute with the name of the function called by the on-click event.
This way it's easy to tell what arguments are going to be passed to the function just from looking at the html, and works for multiple event handlers on the same element.

Event target as a returned value in javascript

Does anyone know how can I access an event target?
i.e, say I have a function:
func(event){...}
so that parameter "event" is a string which describes the event name (such as "onclick"/"onload" etc.), how can I get the target of this?
Suppose the given parameter is "onclick" and the click that happened was on a button called "button1", how can I get button1 as a returned value?
Thanks!
Unless you edited the function context (as with $.proxy), then you can use this to get the current element (and $(this) will return the jquery object).
Regardless if you did edit the context, you can always use event.currentTarget (or $(event.currentTarget) for the jQuery object, again)

Can someone explain why this is passing in an object

I have something like the following..
$(document).ready(function() {
$('#doReport').click(doReport);
});
function doReport(type) {
if (type === undefined) {
type = 'blah';
}
alert (type);
}
If I run doReport() from the console or standalone in the javascript with nothing in it, it will return 'blah' (as expected), and obviously if I call doReport('wibble'); it returns 'wibble' as you would expect.
But if I run it by clicking the element with ID doReport (utilising the bind I set up in .ready) it returns [object Object]
I don't understand why that would be the case.
The jQuery library passes your event handlers an "event" object. It will always be there. It's a "wrapped" or "fixed" version of the native browser object, making it somewhat easier to deal with.
Here is the documentation for such objects.
Also of note is the fact that jQuery will invoke your handler functions such that this refers to the DOM element for which the handler is being invoked.
Also also, as #Ericson578 points out in a good comment, jQuery allows additional parameters to be set up, which means that your handler may be passed additional parameters. That might be useful if you've got a single event handler function to be bound to different elements, but you'd like to qualify its behavior with some different flags or whatever based on the particulars of an element.
Event handlers receive an event object as a parameter.
This is because event handlers are triggered with an object (specifically, the event object) passed as the first argument.
This is the reason you see such syntax as
$('#doReport').click(function(e) {
If you want to call your function without any parameters, you'll need to create a wrapping function to do so:
$(document).ready(function() {
$('#doReport').click(function() {
doReport();
});
});
When jQuery calls the function passed as parameter to click, it passed event object as the argument hence you are getting the alert as [object Object].
Check this:
http://api.jquery.com/click/
From JQuery - .click()
.click( handler(eventObject) )
handler(eventObject)A function to execute each time the event is triggered.
Your doReport() function is getting an event object.
wrap it with another function if you need to pass an argument to your function.
$(document).ready(function() {
$('#doReport').click(function(event){
doReport('blah');
});
});

Categories