How to use mobx - 10 common examples

To help you get started, we’ve selected a few mobx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aksonov / statem / test / gen.js View on Github external
it("redirect to promo scene", function(done){
    statem.start();
    expect(statem.promoScene.active).to.be.false;
    when (()=>statem.promoScene.active, done);
  });
  // it("expect login scene with history", function(done){
github mobxjs / mobx-utils / test / create-view-model.ts View on Github external
function tests(model) {
    const viewModel = utils.createViewModel(model)
    let tr
    let vr
    // original rendering
    const d1 = mobx.autorun(() => {
        tr =
            model.title +
            ":" +
            model.done +
            ",interested:" +
            model.usersInterested.slice().toString() +
            ",unobservedProp:" +
            model.unobservedProp +
            ",usersCount:" +
            model.usersCount
    })
    // view model rendering
    const d2 = mobx.autorun(() => {
        vr =
            viewModel.title +
            ":" +
github chameleon-team / chameleon-runtime / test / .chameleon / web / src / platform / common / proto / WexRuntimeCore.js View on Github external
function dataExprFn() {
      oldVal = curVal
      curVal = exprType === 'string' ? getByPath(context, expr) : expr.call(context)
      if (handler.deep) {
        curVal = toJS(curVal, false)
      } else if (isObservableArray(curVal)) {
        // 强制访问,让数组被观察
        curVal.peek()
      }
      return curVal
    }
github zooniverse / front-end-monorepo / packages / lib-classifier / src / store / ClassificationStore.js View on Github external
width: window.innerWidth,
            height: window.innerHeight
          }
        }

        const feedback = getRoot(self).feedback
        if (feedback.isValid) {
          metadata.feedback = toJS(feedback.rules)
        }

        // TODO store intervention metadata if we have a user...
        self.updateClassificationMetadata(metadata)

        classification.completed = true
        // Convert from observables
        const classificationToSubmit = toJS(classification, { exportMapsAsObjects: false })
        delete classificationToSubmit.id // remove temp id
        classificationToSubmit.annotations = convertMapToArray(classificationToSubmit.annotations)

        const convertedMetadata = {}
        Object.entries(classificationToSubmit.metadata).forEach((entry) => {
          const key = _.snakeCase(entry[0])
          convertedMetadata[key] = entry[1]
        })
        classificationToSubmit.metadata = convertedMetadata

        const subject = getRoot(self).subjects.active
        self.onComplete(classification.toJSON(), subject.toJSON())

        if (process.browser) {
          console.log('Completed classification', classificationToSubmit)
        }
github TerriaJS / terriajs / lib / ViewModels / createGlobalBaseMapOptions.ts View on Github external
CommonStrata.user,
      "layers",
      "nasa-black-marble:dnb_land_ocean_ice.2012.54000x27000_geo"
    );
    blackMarble.setTrait(CommonStrata.user, "opacity", 1.0);
    blackMarble.loadMapItems();
  });
  result.push(
    new BaseMapViewModel(
      blackMarble,
      require("../../wwwroot/images/black-marble.png")
    )
  );

  const positron = new OpenStreetMapCatalogItem("basemap-positron", terria);
  runInAction(() => {
    positron.setTrait(CommonStrata.user, "name", "Positron (Light)");
    positron.setTrait(
      CommonStrata.user,
      "url",
      "https://global.ssl.fastly.net/light_all/"
    );

    // https://cartodb.com/basemaps/ gives two different attribution strings. In any case HTML gets swallowed, so we have to adapt.
    // 1 '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ©
    //   <a href="http://cartodb.com/attributions">CartoDB</a>'
    // 2 Map tiles by <a href="http://cartodb.com/attributions#basemaps">CartoDB</a>, under <a href="https://creativecommons.org/licenses/by/3.0/">
    //   CC BY 3.0</a>. Data by <a href="http://www.openstreetmap.org/">OpenStreetMap</a>, under ODbL.
    positron.setTrait(
      CommonStrata.user,
      "attribution",
      "© OpenStreetMap contributors ODbL, © CartoDB CC-BY 3.0"
github 500tech / angular-tree-component / lib / components / tree-node-collection.component.ts View on Github external
ngOnInit() {
    this.virtualScroll = this.treeModel.virtualScroll;
    this._dispose = [
      // return node indexes so we can compare structurally,
      reaction(() => {
        return this.virtualScroll.getViewportNodes(this.nodes).map(n => n.index);
      }, (nodeIndexes) => {
          this.viewportNodes = nodeIndexes.map((i) => this.nodes[i]);
        }, { compareStructural: true, fireImmediately: true } as any
      ),
      reaction(() => this.nodes, (nodes) => {
        this.viewportNodes = this.virtualScroll.getViewportNodes(nodes);
      })
    ];
  }
github mobxjs / mobx-utils / src / computedFn.ts View on Github external
const self = this
        const entry = d.entry(args)
        // cache hit, return
        if (entry.exists()) return entry.get().get()
        // if function is invoked, and its a cache miss without reactive, there is no point in caching...
        if (!opts.keepAlive && !_isComputingDerivation()) {
            if (!memoWarned) {
                console.warn(
                    "invoking a computedFn from outside an reactive context won't be memoized, unless keepAlive is set"
                )
                memoWarned = true
            }
            return fn.apply(self, args)
        }
        // create new entry
        const c = computed(
            () => {
                return fn.apply(self, args)
            },
            {
                ...opts,
                name: `computedFn(${fn.name}#${++i})`
            }
        )
        entry.set(c)
        // clean up if no longer observed
        if (!opts.keepAlive)
            onBecomeUnobserved(c, () => {
                d.entry(args).delete()
            })
        // return current val
        return c.get()
github ascoders / gaea-editor / gaea-editor / actions / viewport.ts View on Github external
onInit() {
        // 监听当前编辑组件变化
        observe(this.viewport, 'currentEditComponentMapUniqueKey', (newValue: string, oldValue: string) => {
            // 过 150 毫秒再显示编辑区域,不让动画被阻塞
            setTimeout(() => {
                this.viewport.showEditComponents = !!newValue
            }, 150)

            const selectClass = 'gaea-selected'

            // 把上一个元素选中样式置空
            if (oldValue !== null) {
                const prevEditDom = this.viewport.componentDomInstances.get(oldValue)
                if (hasClass(prevEditDom, selectClass)) {
                    removeClass(prevEditDom, selectClass)
                }
            }

            // 设置新元素为选中样式
github PacktPublishing / MobX-Quick-Start-Guide / src / Chapter07 / object-api.js View on Github external
export const ObjectAPIExample = asComponent(() => {
    class Todo {
        @observable description = '';
        @observable done = false;

        constructor(description) {
            this.description = description;
        }
    }

    const firstTodo = new Todo('Write Chapter');
    const todos = observable.array([firstTodo]);

    // eslint-disable-next-line
    const todosMap = observable.map({
        'Write Chapter': firstTodo,
    });

    // Reactions to track changes
    autorun(() => {
        console.log(`metadata present: ${has(firstTodo, 'metadata')}`);
        console.log(get(firstTodo, 'metadata'), get(firstTodo, 'user'));
        console.log(keys(firstTodo));
    });
    autorun(() => {
        // Arrays
        const secondTodo = get(todos, 1);
        console.log('Second Todo:', toJS(secondTodo));
github zenprotocol / explorer / src / store / UIStore.js View on Github external
setTableData({ nameOfIdentifier: 'asset', objectToSet: state.assetKeyholdersTable })
  );
  const setRepoVotesTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.repoVotesTable })
  );
  const setRepoVoteResultsTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.repoVoteResultsTable })
  );
  
  const setCGPAllocationVotesTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.cgpAllocationVotesTable })
  );
  const setCGPPayoutVotesTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.cgpPayoutVotesTable })
  );
  const setCGPAllocationResultsTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.cgpAllocationResultsTable })
  );
  const setCGPPayoutResultsTableData = action(
    setTableData({ nameOfIdentifier: 'interval', objectToSet: state.cgpPayoutResultsTable })
  );
  // add also setters to control both types at the same time
  const setCGPVotesTablesData = action((params = {}) => {
    setCGPAllocationVotesTableData(params);
    setCGPPayoutVotesTableData(params);
  });
  const setCGPVoteResultsTablesData = action((params = {}) => {
    setCGPAllocationResultsTableData(params);
    setCGPPayoutResultsTableData(params);
  });

  const saveToStorage = action(state => {