mobx#action JavaScript Examples

The following examples show how to use mobx#action. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: action-context.js    From albedo with MIT License 6 votes vote down vote up
constructor() {
        makeObservable(this, {
            status: observable,
            intentRequests: observable,
            origin: observable,
            networkParams: observable,
            intentParams: observable.shallow,
            intentErrors: observable,
            runtimeErrors: observable,
            requestedPubkey: observable,
            selectedAccount: observable,
            selectedAccountInfo: observable,
            isBatchRequest: computed,
            reset: action,
            setIntentError: action,
            confirmRequest: action,
            setStatus: action,
            selectAccount: action,
            cancelAction: action,
            loadSelectedAccountInfo: action
        })
    }
Example #2
Source File: uploader.js    From content-components with Apache License 2.0 6 votes vote down vote up
decorate(Uploader, {
	uploads: observable,
	uploadsInProgress: observable,
	statusWindowVisible: observable,
	successfulUpload: observable,
	getUploads: action,
	uploadFile: action,
	uploadFiles: action,
	clearCompletedUploads: action
});
Example #3
Source File: AdminStore.js    From front-app with MIT License 6 votes vote down vote up
@action
  async getFile(name) {
    const response = await api.getFile(name)

    if (name === 'timetable') {
      this.timetable = response
        .replace(/\"/g, '')
        .split('\n')
        .map((data) => {
          return data.split(',')
        })
    } else {
      this.chatlog = response
        .replace(/\"/g, '')
        .split('\n')
        .map((data) => {
          return data.split(',')
        })
    }

    return response
  }
Example #4
Source File: PermissionInfoStore.js    From choerodon-front-base with Apache License 2.0 6 votes vote down vote up
@action
  loadData(pagination = this.pagination, params = this.params) {
    const { id } = this.role;
    this.loading = true;
    this.params = params;
    return axios.get(`/iam/choerodon/v1/users/${id}/roles?${queryString.stringify({
      page: pagination.current,
      size: pagination.pageSize,
      params: params.join(','),
    })}`)
      .then(action(({ failed, list, total }) => {
        if (!failed) {
          this.permissionData = list;
          this.pagination = {
            ...pagination,
            total,
          };
        }
        this.loading = false;
      }))
      .catch(action((error) => {
        Choerodon.handleResponseError(error);
        this.loading = false;
      }));
  }
Example #5
Source File: account-manager.js    From albedo with MIT License 6 votes vote down vote up
constructor() {
        makeObservable(this, {
            selectorVisible: observable,
            activeAccount: observable,
            accounts: observable.shallow,
            setActiveAccount: action,
            loadAvailableAccounts: action,
            addAccount: action
        })
    }
Example #6
Source File: SyncStore.js    From lens-extension-cc with MIT License 6 votes vote down vote up
// NOTE: this method is not just called when reading from disk; it's also called in the
  //  sync process between the Main and Renderer threads should code on either thread
  //  update any of the store's properties
  @action // prevent mobx from emitting a change event until the function returns
  fromStore(store) {
    // NOTE: don't gate this with DEV_ENV because we want to do it every time so we
    //  can detect an invalid store JSON file that a user may have edited by hand
    const result = rtv.check({ store }, { store: storeTs });

    if (!result.valid) {
      logger.error(
        'SyncStore.fromStore()',
        `Invalid data found, will use defaults instead; error=${logValue(
          result.message
        )}`
      );
    }

    const json = result.valid ? store : SyncStore.getDefaults();

    logger.log(
      'SyncStore.fromStore()',
      `Updating store to: ${Object.entries(json)
        .map(([key, value]) => `${key}=${value.length}`)
        .join(', ')}`
    );

    Object.keys(json).forEach((key) => {
      this[key] = json[key];
    });

    logger.log(
      'SyncStore.fromStore()',
      // NOTE: just using defaults to iterate over expected keys we care about on `this`
      `Updated store to: ${Object.keys(SyncStore.getDefaults())
        .map((key) => `${key}=${this[key].length}`)
        .join(', ')}`
    );
  }
Example #7
Source File: authorization.js    From albedo with MIT License 6 votes vote down vote up
constructor() {
        makeObservable(this, {
            dialogOpen: observable,
            reset: action,
            requestAuthorization: action
        })
        this.sessions = {}

        setTimeout(() => { //TODO: address the loading sequence problem and rewrite this dirty hack
            navigation.history.listen((location, action) => {
                this.dialogOpen = false // hide auth dialog when navigation occurred
            })
        }, 200)

        setInterval(() => {
            const now = new Date().getTime()
            for (let key of Object.keys(this.sessions))
                if (this.sessions[key].expires < now) {
                    delete this.sessions[key]
                }
        }, 5000)
    }
Example #8
Source File: asyncDataStore.js    From covidcg with MIT License 6 votes vote down vote up
@action
  async fetchData() {
    this.status = ASYNC_STATES.STARTED;
    fetch(hostname + '/init')
      .then((res) => {
        if (!res.ok) {
          throw res;
        }
        return res.json();
      })
      .then((data) => {
        runInAction(() => {
          this.data = data;
          this.status = ASYNC_STATES.SUCCEEDED;
        });
      })
      .catch((err) => {
        runInAction(() => {
          this.status = ASYNC_STATES.FAILED;
        });
        let prefix = 'Error getting initial data';
        if (!(typeof err.text === 'function')) {
          console.error(prefix, err);
        } else {
          err.text().then((errMsg) => {
            console.error(prefix, errMsg);
          });
        }
      });
  }
Example #9
Source File: routing-store.js    From content-components with Apache License 2.0 6 votes vote down vote up
decorate(RoutingStore, {
	// props
	page: observable,
	queryParams: observable,
	subView: observable,
	// actions
	setRouteCtx: action,
	setPage: action,
	setSubView: action
});
Example #10
Source File: appStore.js    From aircon with GNU General Public License v3.0 6 votes vote down vote up
//当前登录用户信息

  @action toggleLogin(flag, info = {}) {
    this.loginUser = info; //设置登录用户信息
    if (flag) {
      authenticateSuccess(info.username);
      this.isLogin = true;
    } else {
      localStorage.removeItem('accessToken');
      logout();
      this.isLogin = false;
    }
  }
Example #11
Source File: ProgressHUD.js    From RRWallet with MIT License 6 votes vote down vote up
/**
   * Toast提示框
   * 可传入text, icon做定制化
   *
   * @param { HUD_STATUS_SUCCESS | HUD_STATUS_FAILED | HUD_STATUS_CUSTOM } [status=HUD_STATUS_SUCCESS]
   * @param {*} text
   * @param {*} icon
   * @memberof ProgressHUD
   */
  @action show(status = HUD_STATUS_SUCCESS, text, icon) {
    this.type = HUD_TYPE_TOAST;
    this.status = status;
    this.text = text;
    this.icon = icon;
    this.isVisible = true;
  }
Example #12
Source File: appStore.js    From discern with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
//当前登录用户信息

  @action toggleLogin(flag,info={}) {
    this.loginUser = info  //设置登录用户信息
    if (flag) {
      authenticateSuccess(info.username)
      this.isLogin = true
    } else {
      logout()
      this.isLogin = false
    }

  }
Example #13
Source File: OrganizationStore.js    From choerodon-front-base with Apache License 2.0 5 votes vote down vote up
@action
  setParams() {
    this.params = [];
  }
Example #14
Source File: store.js    From aircon with GNU General Public License v3.0 5 votes vote down vote up
@action setCurrent(current) {
    this.current = current;
  }
Example #15
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
@Bind()
  @action
  setValue(newData) {
    super.setValue(newData || '');
  }
Example #16
Source File: appStore.js    From discern with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@action initUsers() {
    const localUsers = localStorage['users']?JSON.parse(localStorage['users']):[]
    this.users = [{username: 'admin', password: 'admin'},...localUsers]
  }
Example #17
Source File: OrganizationStore.js    From choerodon-front-base with Apache License 2.0 5 votes vote down vote up
@action
  setFilters() {
    this.filters = {};
  }
Example #18
Source File: QueryStore.jsx    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
decorate(QueryStore, {
    query: observable,
    setQuery: action,
});
Example #19
Source File: NotificationStore.js    From surveillance-forms with MIT License 5 votes vote down vote up
decorate(NotificationStore, {
  open: observable,
  message: observable,
  durationMs: observable,
  onClose: observable,
  showMessage: action
});
Example #20
Source File: notifications.js    From albedo with MIT License 5 votes vote down vote up
constructor() {
        makeObservable(this, {
            notification: observable,
            showNotification: action,
            closeNotification: action
        })
    }
Example #21
Source File: ProgressHUD.js    From RRWallet with MIT License 5 votes vote down vote up
@action async dismiss() {
    this.view && (await this.view.animate("fadeOut", 200));
    this.isVisible = false;
  }
Example #22
Source File: metadataStore.js    From covidcg with MIT License 5 votes vote down vote up
@action
  async fetchMetadataFields() {
    rootStoreInstance.UIStore.onMetadataFieldStarted();

    fetch(hostname + '/metadata', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        start_date: toJS(rootStoreInstance.configStore.startDate),
        end_date: toJS(rootStoreInstance.configStore.endDate),
        subm_start_date: toJS(rootStoreInstance.configStore.submStartDate),
        subm_end_date: toJS(rootStoreInstance.configStore.submEndDate),
        ...rootStoreInstance.configStore.getSelectedLocations(),
        selected_metadata_fields:
          rootStoreInstance.configStore.getSelectedMetadataFields(),
      }),
    })
      .then((res) => {
        if (!res.ok) {
          throw res;
        }
        return res.json();
      })
      .then((metadataRecords) => {
        // Each row in this array of records is structured as:
        // { "field", "val_id", "count", "val_str" }
        metadataRecords.forEach((record) => {
          this.metadataMap.get(record.field).set(record.val_id, record.val_str);
          this.metadataCounts
            .get(record.field)
            .set(record.val_id, record.count);
        });

        rootStoreInstance.UIStore.onMetadataFieldFinished();
      })
      .catch((err) => {
        if (!(typeof err.text === 'function')) {
          console.error(err);
        } else {
          err.text().then((errMsg) => {
            console.error(errMsg);
          });
        }
        rootStoreInstance.UIStore.onMetadataFieldErr();
      });
  }
Example #23
Source File: CloudStore.js    From lens-extension-cc with MIT License 5 votes vote down vote up
// NOTE: this method is not just called when reading from disk; it's also called in the
  //  sync process between the Main and Renderer threads should code on either thread
  //  update any of the store's properties
  @action // prevent mobx from emitting a change event until the function returns
  fromStore(store) {
    // NOTE: don't gate this with DEV_ENV because we want to do it every time so we
    //  can detect an invalid store JSON file that a user may have edited by hand
    const result = rtv.check({ store }, { store: storeTs });

    if (!result.valid) {
      logger.error(
        'CloudStore.fromStore()',
        `Invalid data found, will use defaults instead; error=${logValue(
          result.message
        )}`
      );
    }

    const json = result.valid ? store : CloudStore.getDefaults();

    logger.log(
      'CloudStore.fromStore()',
      `Updating store to: clouds=[${Object.keys(json.clouds).join(', ')}]`
    );

    Object.keys(json).forEach((key) => {
      if (key === 'clouds') {
        // restore from a map of cloudUrl to JSON object -> into a map of cloudUrl
        //  to Cloud instance
        const existingClouds = this.clouds || {};
        const newClouds = Object.entries(json[key] || {}).reduce(
          (cloudMap, [cloudUrl, cloudJson]) => {
            let cloud;
            if (existingClouds[cloudUrl]) {
              // update existing Cloud with new data instead of creating a new instance
              //  so that currently-bound objects don't leak and those watching for changes
              //  get notified by various Cloud events
              cloud = existingClouds[cloudUrl].update(cloudJson, true);
            } else {
              // add new Cloud we don't know about yet
              cloud = new Cloud(cloudJson, this.ipcMain);
              this.listenForChanges(cloud);
            }

            cloudMap[cloudUrl] = cloud;
            return cloudMap;
          },
          {}
        );

        // make sure we properly remove any old/deleted Clouds
        Object.keys(existingClouds).forEach((cloudUrl) => {
          if (!newClouds[cloudUrl]) {
            this.stopListeningForChanges(existingClouds[cloudUrl]);
            existingClouds[cloudUrl].destroy();
          }
        });

        // this assignment will implicitly remove any old clouds from the map since
        //  they won't be included in `newClouds`
        this.clouds = newClouds;
      } else {
        this[key] = json[key];
      }
    });

    logger.log(
      'CloudStore.fromStore()',
      `Updated store to: clouds=[${Object.keys(this.clouds).join(', ')}]`
    );
  }
Example #24
Source File: GeneralSettingStore.js    From choerodon-front-base with Apache License 2.0 5 votes vote down vote up
@action setProjectInfo(data) {
    this.projectInfo = data;
  }
Example #25
Source File: permission-store.js    From content-components with Apache License 2.0 5 votes vote down vote up
decorate(PermissionStore, {
	// props
	permissions: observable,
	// actions
	setPermissions: action,
});
Example #26
Source File: AdminStore.js    From front-app with MIT License 5 votes vote down vote up
@action
  async handleAdminLogin(data) {
    const response = await api.adminLogin(data)

    return response
  }
Example #27
Source File: store.js    From aircon with GNU General Public License v3.0 5 votes vote down vote up
@action setInfo(info){
    this.info = info
  }
Example #28
Source File: WebinarInfoStore.js    From front-app with MIT License 5 votes vote down vote up
@action
  async getWebinarInfo() {
    const response = await api.getWebinarInfo()
    this.link = response.link
    this.title = response.title
    this.detail = response.detail
    return response
  }
Example #29
Source File: ApplicationSettingStore.js    From choerodon-front-base with Apache License 2.0 5 votes vote down vote up
@action setImageUrl(data) {
    this.imageUrl = data;
  }