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?

Berend Hulshof
  • 1,039
  • 1
  • 16
  • 36

2 Answers2

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.

Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80
  • Thank you, this helped, can you give some additional information on how it works? – Berend Hulshof Mar 23 '18 at 14:23
  • 1
    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. – Dheeraj Kumar Mar 23 '18 at 14:26
  • oh ok, so the brackets indicate the target – Berend Hulshof Mar 23 '18 at 14:43
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);
}
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • Dheeraj's solution is a bit more efficient and it worked, but thanks for the answer – Berend Hulshof Mar 23 '18 at 14:42
  • You can also look at the difference here to get more idea. https://stackoverflow.com/questions/34838294/what-is-difference-between-creating-object-using-object-create-and-object-assi – Amit Chigadani Mar 23 '18 at 14:46