在没有绑定的情况下利用beforeMove/afterMove? [英] utilizing beforeMove/afterMove without a binding?
问题描述
我需要检测何时在 observableArray 中移动项目.在当前版本(2.1.0)中,我通过在所有删除事件上调用setTimeout
并等待看看是否紧随其后的是添加事件来完成此操作:
I need to detect when items are moved in an observableArray. In my current version (2.1.0) I accomplish this by calling setTimeout
on all delete events and waiting to see if an add event follows immediately on its heels:
var delayed = [];
var key; /* obtained by comparing original observableArray with updated list and iterating all differences */
if( /** record exists in original list but not new list ) {
// it was deleted, we don't immediately fire a notification (it may get re-inserted in a moment)
delayed[key] = setTimeout(function() { sendDeleteNotification(key); }, 0);
}
else if( /** record exists in new list but not original */ ) {
if( delayed[key] ) {
// it was deleted and immediately re-added (it's a move)
clearTimeout(delayed[key]);
sendMoveNotification( key );
}
else {
// it was added
sendAddedNotification( key );
}
}
在淘汰赛2.2中,我看到 beforeMove和afterMove的新事件.但是,我找不到任何以编程方式利用它们的方法.
In knockout 2.2, I see new events for beforeMove and afterMove. However, I can't find any means to utilize them programmatically.
最终目标是能够立即在数据库中镜像客户端更改,但不能显示添加/删除来代替移动事件.在列表中上移或下移的记录不应标记为已删除然后重新添加.
The end goal is to be able to mirror client changes in the database immediately, but not show an add/delete in place of a move event. A record moved up or down in the list shouldn't be marked as deleted and then newly added.
可以在JavaScript中直接使用新的beforeMove/afterMove绑定(例如事件模型)来改善这一点吗?
Can the new beforeMove/afterMove bindings be utilized in JavaScript directly (e.g. event model?) to improve this?
干杯
推荐答案
我使用的答案基于此jsfiddle .
beforeMove
和afterMove
函数可以通过简单的订阅来访问:
The beforeMove
and afterMove
functions can be accessed by a simple subscription:
var obs = ko.observableArray();
obs.subscribe(function( arrayOfValues ) {
console.log('moving', arrayOfValues);
}, undefined, 'beforeMove');
obs.subscribe(function( arrayOfValues ) {
console.log('moved', arrayOfValues);
}, undefined, 'afterMove');
但是,事实证明这并不是特别有用,因为它返回更改索引的数组中的所有元素.例如,如果我从列表中删除一条记录,则删除后的每条记录都会得到一个移动的事件.
However, it turns out this wasn't particularly useful as it returns all the elements in the array that change index. For instance, if I delete a record from the list, I get a moved event for every record after the deleted one.
所以我会坚持超时,直到发现更好的地方.
So I'll be sticking with the timeout until I find something better.
这篇关于在没有绑定的情况下利用beforeMove/afterMove?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!