Многоразовые действия в mobx / mobx-state-tree

У меня есть несколько магазинов mobx, и я обнаружил, что в каждом из них есть в значительной степени идентичные действия. Поэтому я надеюсь, что смогу обобщить и повторно использовать их в разных магазинах. Ниже я попытался выделить действие create в надежде, что смогу импортировать его в несколько магазинов, но оно не работает, поскольку self недоступен.

Я хочу уйти от этого:

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const create = flow(function* create(newItem) {
      const newItemRef = firestore.collection(collection).doc()
      const id = newItemRef.id
      self[collection].set(id, newItem)
      yield newItemRef.set(newItem)
      return id
    })
 return {
   create
 }
})

Что-то вроде этого, где действие create можно было бы повторно использовать в других магазинах:

const create = flow(function* create(newItem, collection) {
    const newItemRef = firestore.collection(collection).doc()
    const id = newItemRef.id

    this[collection].set(id, newItem)
    yield newItemRef.set(newItem)

    return id
})

export const CategoriesStore = types
  .model("CategoriesStore", {
  })
  .views(self => ({
  }))
  .actions(self => {
    const collection = "categories"

    const _create = create.bind(self)

    return {
      _create
    }
})

Есть идеи, как этого добиться?


person oskare    schedule 17.07.2019    source источник
comment
Вы говорите, что то, что у вас здесь, не работает?   -  person jayarjo    schedule 19.07.2019
comment
Да, разъяснил это сейчас в вопросе. Спасибо за помощь, отлично работает!   -  person oskare    schedule 19.07.2019


Ответы (1)


Хотя я никогда ничего подобного не делал, но думал и у меня сложилось впечатление, что это должно сработать. Но если этого не произойдет, вы можете сделать что-то вроде:

const create = (self) => flow(function* create(newItem, collection) {
  const newItemRef = firestore.collection(collection).doc()
  const id = newItemRef.id

  self[collection].set(id, newItem)
  yield newItemRef.set(newItem)

  return id
})

export const CategoriesStore = types
.model("CategoriesStore", {
})
.views(self => ({
}))
.actions(self => {
  const collection = "categories"

  return {
    create: create(self)
  }
})

Это определенно должно сработать.

person jayarjo    schedule 19.07.2019