0

So I need to prevent data binding for a specific variable. I want to do it like this:

// data is mostly an object in my case.
// it would be nice if there's a global solution
function(data) {
    d = data; // variable that changes on user input
    oldD = data; // variable that shouldn't change on user input
}

but whenever I implement code like this the oldD variable will change when the d variable gets changed. And I would like to prevent this from happening. But how do I prevent such a thing?

2
  • What kind of variable is data? Is it a primitiv type (number, string, boolean), an array, or an object with properties? Commented Mar 23, 2018 at 14:11
  • sorry, added some extra comments Commented Mar 23, 2018 at 14:21

2 Answers 2

3

You need to assign value without assigning reference of old object.

Here's solution for JavaScript/Angular.

let oldD = Object.assign({}, data);

Hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this helped, can you give some additional information on how it works?
When you use equal sign to copy values, it actually assigns the reference of data. That is how binding works. Multiple vars with same reference. By Object.assign() you just copy the value without the actual reference. So your oldD will have a new reference of its own and hence will not change.
oh ok, so the brackets indicate the target
0

Probably you are looking for, How to clone object.

function(data) {
    d = data; // variable that changes on user input  

    // creates brand new object with the same data
    let oldD = Object.create(data.constructor.prototype);
    data.constructor.apply(oldD);
}

2 Comments

Dheeraj's solution is a bit more efficient and it worked, but thanks for the answer
You can also look at the difference here to get more idea. stackoverflow.com/questions/34838294/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.