码迷,mamicode.com
首页 > 其他好文 > 详细

[MST] Remove Model Instances from the Tree

时间:2018-01-28 11:15:01      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:remove   odi   move   mob   stat   log   []   views   anti   

In this lesson we will dive a bit more into the tree semantics of MST.

In this lesson you will learn:

  • Actions can only modify their own subtree
  • The use of getParent to find the parent of a model instance
  • Using destroy to remove an instance entirely from the tree

 

The whole point for removing data from model is call ‘destroy‘, sometime you might need ‘getParent‘ if the data you want to remove is not in current tree node.

 

import { types, getParent, destroy } from "mobx-state-tree"

export const WishListItem = types
    .model({
        name: types.string,
        price: types.number,
        image: ""
    })
    .actions(self => ({
        changeName(newName) {
            self.name = newName
        },
        changePrice(newPrice) {
            self.price = newPrice
        },
        changeImage(newImage) {
            self.image = newImage
        },
        remove() {
            getParent(self, 2).remove(self)
        }
    }))

export const WishList = types
    .model({
        items: types.optional(types.array(WishListItem), [])
    })
    .actions(self => ({
        add(item) {
            self.items.push(item)
        },
        remove(item) {
            destroy(item)
        }
    }))
    .views(self => ({
        get totalPrice() {
            return self.items.reduce((sum, entry) => sum + entry.price, 0)
        }
    }))

 

[MST] Remove Model Instances from the Tree

标签:remove   odi   move   mob   stat   log   []   views   anti   

原文地址:https://www.cnblogs.com/Answer1215/p/8369681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!