简体   繁体   English

修改敲除.js中的值更改的其他属性

[英]Modify other property on value change in knockout.js

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)? 首次设置date1时(更确切地说,当date2为null时)如何将date2设置为与date1相同的值? 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). 在将数据模型映射到可观察对象时应引入此逻辑/功能(但是,仅在通过数据绑定设置时,date2值在映射时还不应设置为date1值)。

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. 我尝试阅读Knockout JS文档,但未能找到一种方法来拦截如何使用自己的函数来更新date1值。

I am aware of subscribe but it does provide me with just the new value but not the context. 我知道subscribe但是它确实为我提供了新的价值,但没有提供上下文。

You can add subscribe to your date1 observable and set date2 object like this. 您可以像这样添加对您的date1可观察的订阅并设置date2对象。

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/ 小提琴: https : //jsfiddle.net/newuserjs/1m62wpym/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM