ecmascript-object-observe
ecmascript-object-observe copied to clipboard
Array.observe lacks 'move' change type and Array.prototype lacks move(from, to) method
Since Array.observe
may be used to bind some collection model to DOM elements, the move()
method and move
change type are needed to move the nodes associated with collection items. Currently it is only possible to handle addition, removal and replacement of collection items which leads to possibly unnecessary nodes removal and re-additions.
Some example (works in Chrome): http://jsfiddle.net/alexanderby/fd0mrp8j/
As an example .NET's INotifyCollectionChange
has such an action and ObservableCollection
implements a Move
method.
Also Array.prototype.sort()
method should notify of move
change type instead of update
, as far as moved collection item may be collection itself and it's replacement may cause re-creation off associated DOM.
Seems I've found some not beautiful workaround. When going just to move one item, I'm storing from
and to
indices before splice and when the notification comes decide whether to move or add/remove nodes. This is ugly, but allows to work with tree structures without any complex observers (e.g. specifying index paths as from:[1, 3, 4], to:[1,2]
).
Edited previous example: http://jsfiddle.net/fd0mrp8j/7/
So, while creating an ObservableCollection
(which implements Array
interface) for a vector graphics editor's models I ended up with these change types Create
, Replace
, Delete
, Move
, Attach
, Detach
. Also I've extended Array.prototype
with methods move(from, to)
, attach(item, index)
, detach(index)
. Collection notifies of index-properties change events ("0", "1"...) at the end of any method call.
The Move
change occurs when calling move()
, sort()
or reverse()
.
The Attach
and Detach
changes are used when manipulating tree-structures, so the subscriber may store it's detached node at it's holder (e.g. tree controller) or get an attached node. If not a tree, the subscriber may treat these changes as Create
or Delete
.
Each notification is performed for a single item manipulation and the count of necessary notifications is calculated at the end of method call.