更改下拉菜单中的可观察值Jnockout Js [英] Change observable value on dropdown change Knockout Js

查看:73
本文介绍了更改下拉菜单中的可观察值Jnockout Js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个下拉菜单,其中包含车辆是新车还是二手车的选项.

I have this dropdown which have options if vehicle is new or used.

<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">    
    <option value="New" selected="selected">Nuevo</option>
    <option value="Used">Usado</option>
</select> `

此输入:

<input type="text" name="Mileage" data-bind="disable: VehicleType() === 'New',value:  Mileage" class="input-large"> `

如果在下拉列表中选择的值为新建",则必须禁用输入,如果使用,则应启用输入,但是如果我输入一个值,则可观察值将获取该值,并且如果将下拉值更改为新",则可观察值必须变为零.

If the value in the dropdown selected is New the input must be disabled, and if used the input should be enabled, but if I enter a value the observable will grab this value and if I change the dropdown value to new the observable must become zero.

推荐答案

在视图模型中进行手动订阅是处理此类问题的好方法.订阅可能看起来像:

A manual subscription in your view model is a good way to handle something like this. The subscription might look like:

this.VehicleType.subscribe(function(newValue) {
    if (newValue === "New") {
        this.Mileage(0);
    }
}, this);

以下是使用它的示例: http://jsfiddle.net/rniemeyer/h4cKC/

Here is a sample using it: http://jsfiddle.net/rniemeyer/h4cKC/

HTML:

<select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType">
    <option value="New" selected="selected">Nuevo</option> 
    <option value="Used">Usado</option> 
</select>

<input type="text" name="Mileage" data-bind="disable: VehicleType() === 'New', value: Mileage" class="input-large">
<hr/>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

JS:

var ViewModel = function() {
    this.VehicleType = ko.observable();
    this.Mileage = ko.observable();

    this.VehicleType.subscribe(function(newValue) {
        if (newValue === "New") {
            this.Mileage(0);
        }
    }, this);
};

ko.applyBindings(new ViewModel());

这篇关于更改下拉菜单中的可观察值Jnockout Js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆