JSFiddle - React, Tailwind, and code Playground
JavaScript
var myObj = (function () {
var private = "X";
function triggerEvent(eventName) {
if (this[eventName]) {
this[eventName]();
}
}
// Setter / Getter
function getProp() {
return private;
}
function setProp(value) {
private = value;
triggerEvent("onPropChange");
}
// Public API
return {
// Events
"onPropChange": null, // Fires when prop value is changed
// Methods
"getProp": getProp,
"setProp": setProp
};
})();
myObj.setProp("Y"); // --> Nothing happens. Correct
alert(myObj.getProp()); // --> Y - Correct
// Now set event handler
myObj.onPropChange = function () {
alert("You changed the property!");
};
myObj.setProp("Z"); // --> Nothing happens. Wrong
// Why doesn't my alert show?
alert(myObj.getProp()); // --> Z - Correct
// Property has definitely been set