我有一个简单的情况,对象的基本列表(比如汽车)绑定到选择对象(下拉列表)。一旦用户选择它,他就可以更改汽车的价格(出价)。
但是,当更改所选值的价格时,用于填充所选内容的原始列表也会被更新。有没有办法分离或克隆选定的值,以免影响原始数组?
整个想法是使用数组作为用户选择的基础,以便他可以在所选实例(而不是原始列表)中自定义所需的任何属性。
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);
谢谢!
最佳答案
您正在尝试用一种可观察的方式表示两个领域概念:
初始/要价?
出价;
我认为您需要bid
可观察对象的单独构造函数。您可以“拆分”汽车的出价,然后将汽车的价格用作初始出价。如果将汽车的select
绑定到计算的可写观察值,则可以在更改汽车时使用write
位来创建新的出价。
像这样:
var carsListingViewModel = function(availableCars) {
var self = this;
self.availableCars = availableCars;
self.currentBid = ko.observable(null);
_selectedCar = ko.observable();
self.selectedCar = ko.computed({
read: _selectedCar,
write: function(newValue) {
if (newValue !== _selectedCar()) {
_selectedCar(newValue);
self.currentBid(new bid(newValue));
}
}
});
};
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 bid = function(car) {
var self = this;
self.bid = ko.observable(car.Price());
self.car = ko.observable(car);
};
ko.applyBindings(new carsListingViewModel([
new car('Hyundai', 'i30', 100),
new car('Chrysler', '300C', 200)
]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Select a car:<select data-bind="options: availableCars, optionsText: 'Description', value: selectedCar"></select><br/>
<hr/>
<!-- ko with: currentBid -->
You selected: <span data-bind="text: car().Description"></span>.
Bid a price: <input type="text" data-bind="value: bid" />
<!-- /ko -->
关于javascript - 使用 knockout 选项时,如何更新对象实例的属性而不是原始列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31225789/