我有一个如下所示的 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 使用索引对可排序项目进行排序
有没有办法将此可排序索引值绑定(bind)到我的 Position 属性?
这是一个jsFiddle我的代码。
基本上,当一个项目被拖动到新位置时,我想更新 View 模块,以便可以将更改保存回数据库。
最佳答案
对于这样的事情,我喜欢向我的 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/
关于jquery - 将可排序索引值绑定(bind)到 knockout View 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246357/