[英]knockout - computed observable input is not being updated
我有一個動態的項目列表(observableArray),想一次編輯一個。 將輸入字段值綁定到計算后,它似乎只在第一次工作。 對選定元素的進一步更改不會更新輸入字段。 這是代碼:
<DOCCTYPE html>
<html><head>
<script src="jquery-2.1.0.min.js"></script>
<script src="knockout-3.1.0.debug.js"></script>
<style>
.active { background: #EE0; }
</style>
</head><body>
<table><thead><tr>
<th>#</th>
<th>Element ID</th>
</tr></thead>
<tbody data-bind="foreach: elements">
<tr data-bind="css: { active: ((sel() ? sel().id:'') === id) }, click: selectElement">
<td data-bind="text: $index"></td>
<td data-bind="text: id"></td>
</tr>
</tbody></table>
<button data-bind="click: createNew">New element</button>
<h2>Edit current selection</h2>
<label>Color</label><input type="text" data-bind="enable: sel() !== null, value: editColor">
<script>
var elements = ko.observableArray();
var sel = ko.observable(null); // currently selected element
var editColor = ko.computed({
read: function(){
if (!sel()) return '-null-'; // !!! here I'm expecting that due to fact I'm using this observable element inside this computable will be re-eavlued whenever I change sel element and therefore input field will be updated as well
return sel().color;
},
write: function(val){
sel().color = val;
$('#' + sel().id).css('background-color', val);
}
});
function selectElement(el){
sel(el);
}
function createNew(){
var id = 'id_' + (Math.floor(Math.random() * 9000) + 1000); // kinda uniq
var newElement = {
id: id,
color: ''
};
var d = document.createElement('div');
d.setAttribute('id', id);
newElement.dom = d;
$(d).css('width', '100')
.css('height', '100')
.css('border', '1px solid #000');
document.body.appendChild(newElement.dom);
elements.push(newElement);
sel(newElement); // here I'm requesting input value to change
}
$(function(){
ko.applyBindings(window);
});
</script>
</body></html>
重現步驟:
1)單擊“新建”-請注意,輸入字段值已如預期的那樣從-null-更改為空字符串。 那是讀
2)在#ABC之類的文本字段中輸入一些值-值已正確更改
3)再次點擊“新”-現在應該更改輸入框中的值,因為el()現在指向我的新元素。 為什么不發生呢?
我的問題是-我將sel()更改為新值,這是讀取的計算函數中的依賴項。 為什么只工作一次? 在這種情況下是否有更好的方法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.