1

Scenario

I've two models one is Expense and other is DailyExpense(which contains an array of Expense) as the name suggest Expense is a just individual item of Expense while DailyExpense holds a bunch of Expense.

import { types } from 'mobx-state-tree';


/**
 * Expense model which holds individual item
 */
export const Expense = types.model({
    name:types.string,
    price:types.number,
    quantity:types.number,    
}).actions(self => ({
    changeName(newName) {
        self.name = newName
    },
    changePrice(newPrice) {
        self.price = newPrice
    },
    changeQuantity(newQuant) {
        self.quantity = newQuant
    },
})).views(self => ({
    get totalPrice () {
        return self.price * self.quantity
    }
}))


/**
 * DailyExpense model which have arrays of Expense 
 * Also have date as unique identifier
 */
export const DailyExpense = types.model({
    date:types.string,
    items:types.optional(types.array(Expense),[])
}).actions(self => ({
    changeDate (newDate) {
        self.date = newDate
    },    
    addItem (newItem) {
        self.items.push(newItem)
    },
    removeItem (name) {
        const index = self.items.findIndex(e => {
            if(e.name === name) 
                return e
        })
        self.items.splice(index,1)
    }
})).views(self => ({
    get totalPrice () {
        return self.items.reduce((sum,entry) => sum+(entry.price * entry.quantity),0)
    }
}))

Question

Is it possible to create a model for tracking my all DailyExpense

I know I can create one more model where I can do something like this

export const ExpenseList = types.model({
    list:types.array(DailyExpense)
})

But Can I create the model without giving any variable in it like here without a list, something like this?(I know this won't work, I've tried this)

export const ExpenseList = types.model(types.array(DailyExpense))

I've tried creating following model

export const ExpenseList = types.model(types.array(DailyExpense))
.actions(self => ({
    add (s) {
        self.push(s);
    }
}))

And I run following test case but it gave me an error [mobx-state-tree] Functions are not supported as properties, use views instead

it ('can add in list', () => {
  const dailyExpense = DailyExpense.create ({
    date: today,    
    items: [
      {name: 'First Item', price: 20, quantity: 4},
      {name: 'Second Item', price: 10, quantity: 2},
      {name: 'Third Item', price: 5, quantity: 1}
    ],
  });
  const expenseList = ExpenseList.create(dailyExpense);

  expect(expenseList.length).toBe(1);
});
4

1 回答 1

0

不,目前不支持 :)

于 2018-04-29T20:11:33.973 回答