How can I handle a scenario where I need to update a read-only property in the JS script?

97    Asked by david_2585 in Salesforce , Asked on Jun 24, 2024

Imagine there is a scenario where I am currently working on a web development project where I have a javascript object that represents the profile information of the users. This object has a property called “email” which is initially set as read-only because it is retrieved from an API and should not be modified directly. However, I need to update this “email” property due to a user action. How can I handle this particular scenario without violating the read-only property constraint? 

Answered by Dominic Poole

 In the context of Salesforce, you handle the scenario where you need to update a read-only property in a javascript object, by using the concept of property descriptors and object.defineProperty() or object.defineproperties().

Here is how you can do so:-

// Define the user object with a read-only email property

Let user = {
  Name: “John Doe”,
  Get email() {
    Return john.doe@example.com;
  }
};

// Attempt to modify the read-only email property

Try {
  User.email = newemail@example.com; // This will throw an error
} catch (error) {
  Console.error(“Error:”, error.message);
}

// Define a new writable email property using Object.defineProperty

Object.defineProperty(user, “email”, {
  Value: newemail@example.com,
  Writable: true,
  Enumerable: true,
  Configurable: true
});

Console.log(“Updated Email:”, user.email); // Outputs: Updated Email: newemail@example.com

Here is the example given in python programming:-

Class UserProfile:
    Def __init__(self, name, email):
        Self._name = name
        Self._email = email
    @property
    Def email(self):
        Return self._email
    @email.setter
    Def email(self, new_email):
        If hasattr(self, ‘_email’) and not hasattr(self, ‘_email_updated’):
            Self._email_updated = True
            Self._email = new_email
        Else:
            Raise AttributeError(“Cannot assign to read-only property ‘email’”)
# Creating an instance of UserProfile
User_profile = UserProfile(“John Doe”, john.doe@example.com)
# Trying to directly assign a new email (will raise an error)

Try:

    User_profile.email = newemail@example.com
Except AttributeError as e:
    Print(“Error:”, e)
# Updating email using setter method
User_profile.email = newemail@example.com
Print(“Updated Email:”, user_profile.email) # Outputs: Updated Email: newemail@example.com

Here is the example given in HTML :-


    Document.getElementById(“updateEmailBtn”).addEventListener(“click”, function() {
      Var emailInput = document.getElementById(“email”);
      Var newEmail = prompt(“Enter new email:”);
      If (newEmail && newEmail !== “”) {
        emailInput.value = newEmail;
      }
    });

  [removed]





Your Answer

Interviews

Parent Categories