Javascript Essential for Salesforce Developer
An event listener is a JavaScript function that will be called when the specified event occurs on the element.
There are many different types of events in JavaScript, such as mouse events (click, mouseover, etc.), keyboard events (keypress, keydown, etc.), and form events (submit, change, etc.).
Event Listener
To attach an event listener to an element, you use the addEventListener() method, available on all DOM elements. The first argument to addEventListener() is the type of event you want to listen for (e.g., "click", "submit", "load"), and the second argument is the function that should be executed when the event occurs. For example:
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button was clicked!");
});var button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button was clicked!");
});button.addEventListener("click", function(event) {
console.log(event.target); //log the button element
console.log(event.type); //log the event type 'click'
console.log(event.timeStamp);//log the time of the event
});
It's also possible to remove the event listener as well.
button.removeEventListener("click", myFunction);
There are other ways to handle events in JavaScript, such as using the on prefix
Event object
In JavaScript, when an event is triggered on an element, an event object is automatically passed as an argument to the event listener function.
The event object is a standard JavaScript object and is often referred to as the event or e object. It has various properties that provide information about the event, such as:
type: The type of event (e.g., "click", "submit", "load")
target: The element that triggered the event (e.g., the button that was clicked)
currentTarget: The element that the event listener is attached to (it's the same as this inside the function)
timeStamp: The number of milliseconds since the document was loaded, indicating when the event occurred
preventDefault(): A method to stop the default behaviour of the event
stopPropagation(): A method to stop the event from bubbling up to parent elements
// Prevent Default Behaviour of an element
It's also possible to use the preventDefault() and stopPropagation() method to halt the event's default behaviour and stop it from bubbling up to parent elements.
button.addEventListener("click", function(event) {
event.preventDefault();
event.stopPropagation();
});
By calling preventDefault() on the event object, the browser's default behaviour is cancelled. The form will not be submitted, or the link will not navigate to the destination, allowing you to handle the event with JavaScript instead.
It doesn't stop the event from propagating to parent elements you can use stopPropagation() method for that. Also, the effect of preventDefault() can vary between different types of events, so you should be aware of the expected behaviour of the events you are handling
Event Buubling -
Before using stopPropagation() , when a click event occurs on the child(i.e. button), the event Listener of the child is triggered as well as that of the parent.
After adding stopPropagation() , when we do the same, both event Listeners are triggered individually respective to their currentTarget.
Custom Events in JS
To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality.
// Create a custom event start using event Constructor -
// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);
// Using Custom Event
// create custom events
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
const element = document.createElement("div"); // create a <div> element
// add an appropriate event listener
element.addEventListener("animalfound", (e) => console.log(e.detail.name));
// dispatch the events
element.dispatchEvent(catFound);
element.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console
Optional Chaining in Javascript -
get options() {
return (
this.picklistValues?.picklistFieldValues?.[this.sfFieldApiName]?.values ?? []
);
}
this.picklistValues?.picklistFieldValues?.[this.sfFieldApiName]?.values
this.picklistValues: Refers to an object (likely containing picklist values).- Optional chaining (
?.): This is used to safely access properties that may or may not exist. If the property doesn’t exist, it returnsundefinedwithout throwing an error. picklistFieldValues: Inside thepicklistValuesobject, there's a property calledpicklistFieldValues, which likely holds the actual picklist values for various fields.[this.sfFieldApiName]: Dynamically accesses the picklist values for a specific Salesforce field whose API name is stored inthis.sfFieldApiName.values: After accessing the specific field via its API name, it retrieves the actualvaluesproperty, which likely contains the available picklist values.
3. ?? []
- The nullish coalescing operator (
??): If the value on the left side of this operator isnullorundefined, it will return the value on the right side. []: This serves as the fallback value, so ifthis.picklistValues?.picklistFieldValues?.[this.sfFieldApiName]?.valuesisnullorundefined, an empty array[]will be returned instead.
Comments
Post a Comment