In this lesson we will dive a bit more into the tree semantics of MST.
In this lesson you will learn:
getParentto find the parent of a model instance
destroyto remove an instance entirely from the tree
Instructor: [00:00] We're still missing some features. Let's make sure we also have a button to remove the current item.
[00:07] Besides the editor, we also have a remove button. To onClick is actually pretty simple because that can be directly defined as action on the item. Because item doesn't have any binding issues with this, we can just simply pass the remove action of the item to the onClick handler of this button.
[00:31] Of course, it doesn't work yet because we didn't define the remove action. Let's go back to our model and introduce the remove action.
[00:42] The interesting thing about the action is that they can only modify the object they belong to or any of their children. Removing a wish-list item is actually not a modification of the wish list itself. It's a modification of the collection it belongs to.
[00:59] What we are going to do is that we simply delegate this remove method to the owner of this wish-list item.
[01:09] To find the owner in this wish-list utility, it's called, "Get parent." What we're going to do is, on the parent, we will call, "Remove myself."
[01:21] Now, this two means that if you...I mentioned this wish list being a tree. The two means that we want to go two parents up, so it's basically the same as, "Get parent of get parent." We need to be two up, because one up, then we add some to the items' array. We actually want to invoke a method where we are now going to introduce on the wish list itself.
[01:49] We can simply splash the array with index we are currently looking at, and remove one. This will drop the item from the list just like that, but we can actually express this more simple by using, again, a generic utility called destroy. Destroy just removes an item from the container it lives in.
[02:16] Because a mobx-state-tree is always a tree, every item list lives at one unique location. You can simply destroy and make sure that it's removed from the parents.
Can you delegate the method to remove the item from the top of the tree? Without parent()?
Does MST need to define all action on the top level of the model? Can it be modularized? So the model's nested branch can be defined in a separate file together with some actions to operate only on that branch?
These are quite extensive conceptual questions, best ask them at: https://spectrum.chat/mobx-state-tree where the community can chime in.