React Service单例替代

时间:2018-12-25 15:06:57

标签: reactjs design-patterns redux singleton

我正在使用Google Maps库制作ReactJS应用程序, 我正在尝试将大多数地图逻辑抽象到服务,以便将来可以与传单交换google地图库。

现在的工作方式是,我有一个组件加载地图库并将其附加到div。 onLoad回调将在此服务中设置地图,以便我可以对其进行引用。

onMapLoad={(map: Map) => {
    mapService.setMap(map);
    props.mapLoaded();
}}

例如在地图上选择某个标记时,该服务还需要访问我的redux存储以调度操作。我在引导index.tsx文件中的应用程序时进行设置

const store = getStore();
mapService.setStore(store);

服务本身是一个单例,但是我想知道是否有更好的模式可用于React或只是一般而言。我将发布该服务的简短版本,并为简洁起见省略了一些方法。有没有人提供可以改善这种做法的模式建议?

interface MapService {
    predictPlaces: (query: string) => Observable<AutocompletePrediction[]>;
    setStore: (store: Store<StoreState>) => void;
    addMarkerToMap: (place: Place) => void;
    centerMapAroundSuggestion: (suggestion: Suggestion) => void;
    setMap: (newMap: Map) => void;
}

let predictService: google.maps.places.AutocompleteService;
let geocoder: google.maps.Geocoder;
let map: Map;
let store: Store;
let markers: google.maps.Marker[] = [];

const setMap = (newMap: Map) => {
    map = newMap;
}

const setStore = (store: Store) => {
    store = Store;
}

const centerMapAroundSuggestion = (suggestion: Suggestion) => {
    if (!map) {
        throwGoogleMapsNotLoaded();
    }
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    ... further implementation ...
}

const predictPlaces = (query: string): Observable<AutocompletePrediction[]> => {
    if (!map) {
        return of([]);
    }
    if (!predictService) {
        predictService = new google.maps.places.AutocompleteService();
    }
    ... further implementation ...
}

const addMarkerToMap = (place: Place, onSelect: () => void) => {
    const marker = createMarker(place, onSelect);
    markers.push(marker);
}

const createMarker = (place: Place): Marker => {
    if (!map) {
        throwGoogleMapsNotLoaded();
    }
    const marker = new google.maps.Marker({
        ...options...
    });
    marker.addListener('click', () => {
        createInfoWindow(marker)
        if(!!store) {
            store.dispatch(createMarkerClicked(place))
        }
    });
    ... further implementation ...
}

function throwGoogleMapsNotLoaded() {
    throw new Error('Google maps not loaded');
}

export const mapService: MapService = {
    predictPlaces,
    addMarkerToMap,
    setMap,
    setStore,
    centerMapAroundSuggestion
}

0 个答案:

没有答案