getPos in NodeView still returns old value when new node is inserted

I’m trying to re-use my NodeViews when possible and have implemented a logic based on getPos and attributes to decied if a NodeView can be reused or not.

However, it seems that getPos for existing NodeView still returns the old position when a new node that is rendered using NodeView is inserted. I made an example for this:

If you press the “Add custom node at start” button to insert a NodeView-node at the start of the document where there currently already is one, getPos for both the old and the new NodeView return 0. I would expect getPos for the old NodeView to return 1, since it was moved down. This is the case if you let the callstack finish.

Is this intended behaviour? I wasn’t sure so I wanted to ask here first before reporting it as a bug.

The result in the timeout seems to be the expected behavior. When the new node view is being constructed, the view tree hasn’t finished updating yet, so calling getPos for other node views at that point is not going to give up-to-date results. But that’s not really something you’d reasonably need to do anyway.

I was actually relying on getPos to return the up-to-date value when a new node view is constructed to determine if I can reuse an already existing node view. In my case it happens very often that node views for the same data at the same position get destroyed and then recreated, because they are wrapped with marks.

The logic on how to avoid that I thought of is that if the requested node is at the same position as an already existing node view of the same type and with the same attributes, than I can just re-use that one, since it will be destroyed anyways.

Do you see a way how I could achieve this? I guess this might be misusing the PM API a bit, but I dont really see another way. I my case the node views are videos and re-creating them when a mark is added loses playback position, buffers etc. which I need to avoid.

That’s not going to work. Should be pretty easy to build reuse with the destroy method though (it could add the object to a pool of available objects).

Yeah, that was my initial idea as well. The problem is that in the case I described before (adding a mark to a node), the node view gets created before destroy is called for the old one. This means I would need to know beforehand if I can reuse a not-yet-destroyed node view, hence the whole getPos workaround.