0
votes

How to set the date2 to the same value as date1 when date1 is set for the first time (more precisely, when date2 is null)? This logic/function should be introduced while mapping a data model to an observable (however, the date2 value should not be set to the date1 value on mapping yet, just when set via data binding).

Data Model

var dataModel = {
     'agenda': {
         months: [{date1: null, date2: null}],
     }
}

Binding

data-bind="value: date1"

Mapping

var observableModel = ko.mapping.fromJS(dataModel);

I have tried to read the Knockout JS documentation but failed to find a way how to intercept updating the date1 value with my own function.

I am aware of subscribe but it does provide me with just the new value but not the context.

1

1 Answers

1
votes

You can add subscribe to your date1 observable and set date2 object like this.

ko.utils.arrayForEach(observableModel.agenda.months(), function(obj){
  obj.date1.subscribe(function(){ date2Handler(obj.date1, obj.date2)});  
});

function date2Handler(date1,date2){
    if(date2()==null)
        date2(date1())
}

Fiddle: https://jsfiddle.net/newuserjs/1m62wpym/1/