Data binding 更改下拉列表上的可观察值更改淘汰Js
我有这个下拉列表,如果车辆是新的或使用过的,它可以选择Data binding 更改下拉列表上的可观察值更改淘汰Js,data-binding,knockout.js,observable,Data Binding,Knockout.js,Observable,我有这个下拉列表,如果车辆是新的或使用过的,它可以选择 <select name="VehicleType" id="vehicleTypeDropdown" data-bind="value: VehicleType"> <option value="New" selected="selected">Nuevo</option> <option value="Used">Usado</option> </
<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"> `
`
如果选择的下拉列表中的值是新的,则必须禁用输入,如果使用,则应启用输入,但如果我输入值,则可观察对象将获取此值,如果我将下拉列表中的值更改为新值,则可观察对象必须变为零。在视图模型中手动订阅是处理类似情况的好方法。订阅可能如下所示:
this.VehicleType.subscribe(function(newValue) {
if (newValue === "New") {
this.Mileage(0);
}
}, this);
下面是一个使用它的示例:
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>
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());
如果正在使用,则可以拦截新对象的创建并在那里设置订阅。如果您有一个完整的项目列表,并且希望在发生更改时执行操作
这是购物车行项目的视图模型(属性,如数量
,库存单位
,说明
,价格
)
当您使用映射插件更新(或创建)模型时,您指定对于名为“items”的属性,应使用指定的“create”函数创建数组中的每个元素
var mapping =
{
'items':
{
// map cart item
create: function (options)
{
return new CartItemViewModel(options.data);
}
}
};
var data = ...... // get your data from somewhere
// update the CartViewModel using the mapping rules
ko.mapping.fromJS(data, mapping, rrvm.CartViewModel);
@RP-另一颗宝石!我可以根据自己的需要修改它,使用它将文本字段设置为一个值,给定一个下拉值。谢谢显然,KnockOut JS文档肯定是缺少的,因为我到现在为止还没有看到
.subscribe()
。
var mapping =
{
'items':
{
// map cart item
create: function (options)
{
return new CartItemViewModel(options.data);
}
}
};
var data = ...... // get your data from somewhere
// update the CartViewModel using the mapping rules
ko.mapping.fromJS(data, mapping, rrvm.CartViewModel);