【发布时间】:2015-09-22 09:58:52
【问题描述】:
我有一个简单的案例,其中对象的基本列表(比如说汽车)绑定到一个选择(下拉列表)。一旦用户选择它,他就可以更改汽车的价格(出价)。
但是,当更改所选值的价格时,用于填充选择的原始列表也会更新。有没有办法分离或克隆所选值,使其不会影响原始数组?
整个想法是使用一个数组作为用户选择的基础,这样他就可以在所选实例中自定义他想要的任何属性,而不是在原始列表中。
I have a working fiddle here 代码如下:
HTML:
Select a car:<select data-bind="options: availableCars, optionsText: 'Description', value: selectedCar"></select><br/>
You selected: <span data-bind="text: selectedCar().Description"></span>
<br/>
Bid a price: <input type="text" data-bind="value: selectedCar().Price" />
JS:
var carsListingViewModel = function(availableCars) {
var self = this;
self.availableCars = availableCars;
self.selectedCar = ko.observable();
};
var car = function(make, model, price) {
var self = this;
self.Make = ko.observable(make);
self.Model = ko.observable(model);
self.Price = ko.observable(price);
self.Description = ko.computed(function() {
return self.Make() + ' ' + self.Model() + ' - ' + self.Price();
});
};
var allCars = [
new car('Hyundai', 'i30', 100),
new car('Chrysler', '300C', 200)
];
var model = new carsListingViewModel(allCars);
ko.applyBindings(model);
谢谢!
【问题讨论】:
标签: javascript html knockout.js binding