mirror of
https://github.com/zhigang1992/mobx-utils.git
synced 2026-06-12 17:08:09 +08:00
24 lines
1.0 KiB
TypeScript
24 lines
1.0 KiB
TypeScript
import { computed, _isComputingDerivation } from "mobx"
|
|
|
|
/**
|
|
* expr can be used to create temporarily views inside views.
|
|
* This can be improved to improve performance if a value changes often, but usually doesn't affect the outcome of an expression.
|
|
*
|
|
* In the following example the expression prevents that a component is rerender _each time_ the selection changes;
|
|
* instead it will only rerenders when the current todo is (de)selected.
|
|
*
|
|
* @example
|
|
* const Todo = observer((props) => {
|
|
* const todo = props.todo;
|
|
* const isSelected = mobxUtils.expr(() => props.viewState.selection === todo);
|
|
* return <div className={isSelected ? "todo todo-selected" : "todo"}>{todo.title}</div>
|
|
* });
|
|
*
|
|
*/
|
|
export function expr<T>(expr: () => T): T {
|
|
if (!_isComputingDerivation())
|
|
console.warn("'expr' should only be used inside other reactive functions.")
|
|
// optimization: would be more efficient if the expr itself wouldn't be evaluated first on the next change, but just a 'changed' signal would be fired
|
|
return computed(expr).get()
|
|
}
|