我有一个json结构,如下所示,其中"Position“是一个排序值。
[
{"ID":1, "Title":"Title 1", "Position":1},
{"ID":2, "Title":"Title 2", "Position":2},
{"ID":5, "Title":"Title 3", "Position":3},
{"ID":7, "Title":"Title 4", "Position":99}
];knockout-sortable使用索引对可排序项进行排序。
是否有方法将此可排序索引值绑定到“位置”属性?
这是我的代码的jsFiddle。
基本上,当一个项目被拖到一个新的位置时,我想更新视图模块,这样我就可以将更改保存回数据库。
发布于 2013-06-22 12:52:49
对于这种情况,我喜欢向我的observableArray添加一个订阅,该订阅通过数组进行一次,并正确地设置“索引”。
下面是适用于您的用例的扩展:
ko.observableArray.fn.withIndex = function(prop, startIndex, lastIndex) {
//by default use an "index" observable
prop = prop || "index";
//whenever the array changes, make a single pass through to update the indexes
this.subscribe(function(newValue) {
var item;
for (var i = 0, j = newValue.length; i < j; i++) {
//create the observable if it does not exist
item = newValue[i];
if (!item[prop]) {
item[prop] = ko.observable();
}
//special logic for the last one
item[prop]((lastIndex && i === (j - 1)) ? lastIndex : startIndex + i);
}
}, this);
return this;
};你会把它当作:
myObservableArray.withIndex("Position", 1, 99);下面是您更新的示例:http://jsfiddle.net/rniemeyer/HVNUr/
发布于 2013-06-22 12:14:07
我在列表容器中添加了一个id,这样我就可以“监听”改变它的dom修改。我在timer中包装了更新位置进程,因为dom修改事件被触发了太多次。
var positions = ko.utils.arrayMap(viewModel.Items(), function (item) {
return item.Position();
});
positions.sort();
var itmer = null;
$('#container').bind('DOMNodeInserted DOMNodeRemoved', function () {
if (itmer) clearTimeout(itmer);
itmer = setTimeout(function () {
var items = viewModel.Items();
ko.utils.arrayForEach(items, function (item) {
var index = $('#container [id=' + item.ID() + ']').last().index();
var newPosition = positions[index];
item.Position(newPosition);
});
}, 50);
});See fiddle
希望能帮上忙。
https://stackoverflow.com/questions/17246357
复制相似问题