dustingetz / react-cursor

Immutable state for React.js
1.03k stars 50 forks source link

destroy function? #68

Closed gregwebs closed 8 years ago

gregwebs commented 8 years ago

When removing an element from a list I can hand out a cursor to an item in a list to a child component that owns that piece of data. But there is no way for that child component to destroy itself. Instead it needs a callback from the parent or to dispatch a destroy event (it cannot perform this through the cursor).

If we look at cortex, there is a destroy function. Would this make for a good addition to react-cursor?

Details:

dustingetz commented 8 years ago

This was discussed before in #21. After reflecting for a bit, we decided that delete is a container operation, and should be done on a cursor to the container, which preserves cursor encapsulation - a refined cursor can have no effect on any parent.

So if you want to delete an element from a list, you should use .splice on a cursor to the list.

gregwebs commented 8 years ago

Thanks for the reference to existing discussion, that is helpful! I understand that delete is a container operation. However, I am wondering what harm can come from an array element deleting itself? The only problem I can think of is if some strange reliance on an unchanging index. In the react context this would be if the index of the array is used as a template key.

An alternative, I will probably create a helper for passing in the deletion callback that looks similar to this

_.map(cursor.array, (item, i) => {
  <Child item={cursor.refine(i)} destroy={cursor.deleteAt(i)} />
})

Conceptually this is really just the parent saying "I am ok with the child triggering a deletion". This could also be modeled by setting a property on the cursor cursor.refind(i).destroyable(true) but I tend to prefer the type-safety offered by passing in a separate function.

dustingetz commented 8 years ago

You could also can pass the container-cursor and the index.

Cursors by design provide an unbreakable guarantee that a down-tree cursor cannot modify anything up-tree. It mirrors e.g. Java generics, where an object inside a List can't remove itself from the list. We feel this guarantee is very important.

gregwebs commented 8 years ago

You could also can pass the container-cursor and the index.

But then you are violating the actual guarantee that we want, which is that a child component cannot mess with state that they have no business dealing with. We just want to be able to give permission to a child to destroy itself, not to do anything else.