jsfiddle example。就像标题所说的那样,我正在尝试将计算的可观察值与rniemeyer剔除可排序示例一起使用。我不断
写方法需要实现
在开发人员控制台中可以看到此错误。
我在ko.computed上有一个write方法实现,但仍然出错。我做错了什么?
下面的html和javascript
<div id="main">
<h3>Tasks</h3>
<div class="container" data-bind="sortable: tasks">
<div class="item">
<span data-bind="visible: !$root.isTaskSelected($data)">
<a href="#" data-bind="text: TestName"></a>
</span>
<span data-bind="visibleAndSelect: $root.isTaskSelected($data)">
<input data-bind="value: name, event: { blur: $root.clearTask }" />
</span>
</div>
</div>
</div>
var Task = function(first,last) {
var self = this;
self.firstName = ko.observable(first);
self.lastName = ko.observable(last);
self.TestName = ko.computed({
read: function (){
return self.firstName() + " " + self.lastName();
},
write: function (item) {
console.log(item);
}
});
return self;
}
var ViewModel = function() {
var self = this;
self.testTasks = ko.observableArray([
new Task("test","one"),
new Task("test","two"),
new Task("test","three")
]);
self.tasks = ko.computed({
read: function() { return self.testTasks();},
write: function(item) {console.log(item);}
});
self.selectedTask = ko.observable();
self.clearTask = function(data, event) {
if (data === self.selectedTask()) {
self.selectedTask(null);
}
if (data.name() === "") {
self.tasks.remove(data);
}
};
self.addTask = function() {
var task = new Task("new");
self.selectedTask(task);
self.tasks.push(task);
};
self.isTaskSelected = function(task) {
return task === self.selectedTask();
};
};
//control visibility, give element focus, and select the contents (in order)
ko.bindingHandlers.visibleAndSelect = {
update: function(element, valueAccessor) {
ko.bindingHandlers.visible.update(element, valueAccessor);
if (valueAccessor()) {
setTimeout(function() {
$(element).find("input").focus().select();
}, 0); //new tasks are not in DOM yet
}
}
};
ko.applyBindings(new ViewModel());
最佳答案
正如该插件的作者所说的here一样,您不能使用计算的可观察值。 sortable插件取决于实际的可观察数组。
当您考虑它时,这是有道理的:当您对元素重新排序时,插件实际上是在操纵数组的各种索引。
关于javascript - knockout 排序与计算的可观察无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22491085/