How can I guarantee that my enums definition doesn't change in JavaScript?
Since 1.8.5 it's possible to seal and freeze the object, so define the above as:
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
or
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
and voila! JS enums.
However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.
Quotes aren't needed but I kept them for consistency.
JavaScript - Why doesn't my code run when Document.querySelector().value is outside function + how do I get function to run on input number change?
const number needs to be in the function, otherwise the const will be null always
function myFunction() {
const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
Live update on keyup inputfield
const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);
Why doesn't the value of a field change after form submit (JavaScript/Chrome extension)
Ok I just realized I had this stateless, so when I turned it stateful with React did the job
class TextChanger extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
const task = 'task' in this.state ? this.state.task :
this.props.task;
and then
onTextChange(event) {
this.setState({
task: event.target.value,
});
}
Related Topics
How to Toggle an Element's Class in Pure JavaScript
Jquery to Loop Through Elements with the Same Class
How to Parse a Time into a Date Object from User Input in JavaScript
What's the Best Way to Break from Nested Loops in JavaScript
How to Get Elements with Multiple Classes
Adding Custom Functions into Array.Prototype
(1, Eval)('This') VS Eval('This') in JavaScript
Mobile Safari Autofocus Text Field
What Is the Order of Execution in JavaScript Promises
How Many Bytes in a JavaScript String
How to Set Multiple CSS Styles in JavaScript
Error Parsing Xhtml: the Content of Elements Must Consist of Well-Formed Character Data or Markup
Which Keycode for Escape Key with Jquery
Merge Multiple Objects Inside the Same Array into One Object
Parallel Asynchronous Ajax Requests Using Jquery