当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript Store.subscribe方法代码示例

本文整理汇总了TypeScript中redux.Store.subscribe方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Store.subscribe方法的具体用法?TypeScript Store.subscribe怎么用?TypeScript Store.subscribe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在redux.Store的用法示例。


在下文中一共展示了Store.subscribe方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: return

  return (store: Store<FullState>) => {

    const payload = keeps.reduce(
      (action, { key, storage, load }) => ({ ...action, [key]: load(key, storage), }),
      {}
    );

    store.dispatch({
      payload,
      type: HYDRATE
    });

    const results: { [key: string]: any; } = {};
    store.subscribe(() => {
      const state = store.getState();

      for (const { key, selector, storage, save } of keeps) {
        const result = selector(state);

        if (result !== results[key]) {
          results[key] = result;
          save(key, result, storage);
        }
      }
    });
  };
开发者ID:jakelazaroff,项目名称:redux-keep,代码行数:26,代码来源:index.ts

示例2: subscribeToStateChange

	public subscribeToStateChange(
		listener: Listener,
		options: { handlerIds: string[] | undefined } = { handlerIds: undefined },
	): Unsubscribe {
		const { handlerIds } = options
		invariant(typeof listener === 'function', 'listener must be a function.')
		invariant(
			typeof handlerIds === 'undefined' || Array.isArray(handlerIds),
			'handlerIds, when specified, must be an array of strings.',
		)

		let prevStateId = this.store.getState().stateId
		const handleChange = () => {
			const state = this.store.getState()
			const currentStateId = state.stateId
			try {
				const canSkipListener =
					currentStateId === prevStateId ||
					(currentStateId === prevStateId + 1 &&
						!areDirty(state.dirtyHandlerIds, handlerIds))

				if (!canSkipListener) {
					listener()
				}
			} finally {
				prevStateId = currentStateId
			}
		}

		return this.store.subscribe(handleChange)
	}
开发者ID:chenermeng,项目名称:react-dnd,代码行数:31,代码来源:DragDropMonitorImpl.ts

示例3: didChangeSharedState

 didChangeSharedState (fn: (state: SharedState) => void) {
   this.store.subscribe(() => {
     this.events.emit(STATE_UPDATED_EVENT)
     this.getSharedState().then(sharedState => {
       fn(sharedState)
     })
   })
 }
开发者ID:8001800,项目名称:SpankCard,代码行数:8,代码来源:BackgroundController.ts

示例4: trySubscribe

  public trySubscribe() {
    if (!this.unsubscribe) {
      this.unsubscribe = this.parentSub
        ? this.parentSub.addNestedSub(this.onStateChange)
        : this.store.subscribe(this.onStateChange);

      this.listeners = createListenerCollection();
    }
  }
开发者ID:russelgal,项目名称:inferno,代码行数:9,代码来源:Subscription.ts

示例5: next

  return next => (reducer, initialState: LocalStorage, enhancer) => {
    const store: Store<LocalStorage> = next(reducer, initialState, enhancer)
    const throttleMs = 1000

    store.subscribe(
      _.throttle(() => {
        saveToLocalStorage(store.getState())
      }, throttleMs)
    )

    return store
  }
开发者ID:influxdata,项目名称:influxdb,代码行数:12,代码来源:persistStateEnhancer.ts

示例6: it

  it("doesn't sync if the uiData registration_synchronized value is true", function (done) {
    assert(listener.notCalled);

    fetchMock.mock({
      matcher: uiDataFetchURL,
      response: () => {
        let body = generateGetUIDataResponse({
          [KEY_REGISTRATION_SYNCHRONIZED]: true,
        });
        return { body };
      },
    });

    fetchMock.mock({
      matcher: clusterFetchURL,
      response: () => {
        const encodedResponse = protos.cockroach.server.serverpb.ClusterResponse.encode({ cluster_id: CLUSTER_ID }).finish();
        return {
          body: api.toArrayBuffer(encodedResponse),
        };
      },
    });

    fetchMock.mock({
      matcher: registrationFetchURLPrefixMatcher,
      response: () => {
        done(new Error("Should not have tried to contact the registration server."));
      },
    });

    // Trigger the store subscription.
    store.dispatch({ type: null });
    assert(listener.called);

    // Watch the state and complete the test successfully if we last a tick with
    // the expected information.
    let timeout: number;
    store.subscribe(() => {
      let state = store.getState();
      clearTimeout(timeout);
      if (state.cachedData.cluster.data &&
        state.cachedData.cluster.data.cluster_id &&
        state.uiData[KEY_REGISTRATION_SYNCHRONIZED] &&
        state.uiData[KEY_REGISTRATION_SYNCHRONIZED].data
      ) {
        assert.lengthOf(fetchMock.calls(uiDataFetchURL), 1);
        assert.lengthOf(fetchMock.calls(clusterFetchURL), 1);
        assert.lengthOf(fetchMock.calls(registrationFetchURLPrefixMatcher), 0);
        timeout = setTimeout(() => done());
      }
    });
  });
开发者ID:osguydch,项目名称:cockroach,代码行数:52,代码来源:registrationService.spec.ts

示例7: subscribeToOffsetChange

	public subscribeToOffsetChange(listener: Listener): Unsubscribe {
		invariant(typeof listener === 'function', 'listener must be a function.')

		let previousState = this.store.getState().dragOffset
		const handleChange = () => {
			const nextState = this.store.getState().dragOffset
			if (nextState === previousState) {
				return
			}

			previousState = nextState
			listener()
		}

		return this.store.subscribe(handleChange)
	}
开发者ID:chenermeng,项目名称:react-dnd,代码行数:16,代码来源:DragDropMonitorImpl.ts

示例8: fromJS

const apiHandler = (store: Store<AppState>): void => {
    let prevState: any = fromJS({});
    store.subscribe(throttle((): void => {
        const state = store.getState(); // The state is Immutable Map
        if (state.get("isLoading") === true || state.get("valid") === false) {
            return void 0;
        }
        const prevFmtString = (prevState.get("input") || "").split(" ")[0];
        const currFmtString = (state.get("input") || "").split(" ")[0];
        if (
            typeof prevState.get === "function" &&
            state.get("input").length > 0 &&
            state.get("hexData").length > 0 &&
            (
                prevFmtString !== currFmtString ||
                prevState.get("hexData") !== state.get("hexData")
            )
        ) {
            store.dispatch(actions.startLoading());
            const body: APIBody = {
                formatString: state.get("input"),
                input: state.get("hexData"),
            };
            request.post(API_PATH, body)
                .then((res) => {
                    let data = res.data;
                    if (typeof data === "string") {
                        data = JSON.parse(`${data}`);
                    }
                    store.dispatch(actions.updateResults(data.results));
                    store.dispatch(actions.stopLoading());
                })
                .catch((err: AxiosError) => {
                    const errorMsg = (err.response ? err.response.data.error : err.message) ||
                                     err.message ||
                                     "Unknown Error";
                    store.dispatch(actions.stopLoading());
                    store.dispatch(actions.apiError(errorMsg));
                });
        }
        prevState = state;
    }, REQUEST_INTERVAL));
};
开发者ID:shuntksh,项目名称:binaryscanr,代码行数:43,代码来源:apiRequetHandler.ts

示例9: observeStore

export function observeStore(store:Store<any>, ...args) {
  let onChange = args.pop();
  let selectors = args;
  let currentState;

  function handleChange() {
    const nextState = _.map(selectors, f => f(store.getState()));
    const stateChanged = _(nextState)
      .zip(currentState)
      .some(([x, y]) => (x !== y));

    if (stateChanged) {
      currentState = nextState;
      onChange(...currentState);
    }
  }

  let unsubscribe = store.subscribe(handleChange);
  handleChange();
  return unsubscribe;
}
开发者ID:codeaudit,项目名称:graphql-voyager,代码行数:21,代码来源:redux.ts

示例10: clearTimeouts

const exampleHandler = (store: Store<AppState>): void => {
    let prevState: string = "";
    store.subscribe((): void => {
        const state = store.getState(); // The state is immutable Map.
        const example = state.get("example");
        if (!example || example === prevState) {
            if (prevState && !example) {
                prevState = "";
                clearTimeouts(_timerRef);
            }
            return void 0;
        }
        if (example && example !== prevState) {
            prevState = example;
            let value = "";
            let filter = "";

            if (example === "random") {
                const _arr = new Uint32Array(120);
                (window || global).crypto.getRandomValues(_arr);
                _arr.forEach((item) => value += item.toString(16));
                filter = "b32B32H16H16f2x128a32 bin Bin Hex hex float ascii";
                _exampleReplayer(value, filter, store);
                return void 0;
            }

            if (examples.indexOf(example) > -1) {
                store.dispatch(actions.startLoading());
                // Cancel inflight request (if any)
                if (_cancelTokens.length) {
                    cancelRequests();
                }
                const cancelSource = axios.CancelToken.source();
                _cancelTokens.push(cancelSource);
                fetchExample(example, cancelSource, store);
                return void 0;
            }
        }
    });
};
开发者ID:shuntksh,项目名称:binaryscanr,代码行数:40,代码来源:exampleHandler.ts


注:本文中的redux.Store.subscribe方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。