Can variables be decoupled from two-way binding?


#1

I have a situation where I am using a factory and I fill an array from values from another array. When I change a value in one array, it changes the values in the other array.


#2

Sounds like a basic JavaScript question: you have two variables referring to the same object. Nothing specific to two-way binding. You can use angular.copy to make a… copy.


#3

thank you. that did the trick


#4

Hi encodedmirko, in ionic2/angular2 there is no angular.copy - i’ve tried Object.assign and lodash clone, but so far to no avail - here’s my typescript use case:

  1. let qp: QuickPicker;
  2. let arrivalDepartureDate: Date;
  3. qp = Object.assign(new QuickPicker(dateUtil), applicationService.getQuickPicker());
  4. arrivalDepartureDate = qp.getArrivalDepartureDate();
  5. arrivalDepartureDate = dateUtil.setPickedTimeToDate(pickedTimeDate, arrivalDepartureDate);

As soon as line 5 is executed singleton applicationService with property registration.quickPicker is updated. None of the other method calls reference applicationService. Crazy eh ! I have the feeling that as soon as a relationship in Ionic2 is setup between two variables/objects, changes to one side are reflected immediately in the other side making cloning useless.

In pure javascipt the following even without cloning decouples copy from source:

var applicationService = {a:1, b:2};
var getA = function(){return applicationService.a};
var aCopy = getA(); // 1
aCopy = 11;
getA(); // 1
applicationService.a; // 1

Update: Ok last example is a bad example because here we are updating byValue because primitive type Number is being updated…

Lets try more realistic example where object is updated with and without cloning. With cloning the copy is decoupled from the source:

*** Without cloning ***

  1. applicationService.c = {a:1, b:2}; // Object {a: 1, b: 2, c: Object}
  2. var getC = function(){return applicationService.c}
  3. getC(); // Object {a: 1, b: 2}
  4. var cCopy = getC();
  5. cCopy; // Object {a: 1, b: 2}
  6. cCopy.a; // 1
  7. cCopy.a = 11;
  8. applicationService.c; // Object {a: 11, b: 2} Copy and source not decoupled

*** With cloning ***

  1. var copyClonedC = Object.assign({}, getC())
  2. copyClonedC; // Object {a: 11, b: 2}.
  3. copyClonedC.a; // 11
  4. copyClonedC.a = 111;
  5. applicationService.c; // Object {a: 11, b: 2} Copy and source as required decoupled

Here are my environment details:

Cordova CLI: 6.3.1
Ionic Framework Version: 2.0.0-rc.1
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.38
OS: Windows 7 SP1
Node Version: v6.9.1

Update: My colleague suggested i use lodash cloneDeep and with _.cloneDeep copy and source are decoupled :slight_smile: