我認爲你最好通過實施Flux體系結構來解決這個問題。 Redux非常適合。
爲您的巡迴賽進程創建一個Redux Reducer。此減速器的狀態應該是與用戶所在行程的當前步驟相對應的關鍵。
巡迴賽中使用的所有組件都應該可以作爲道具訪問此巡迴賽狀態。使用此道具來確定功能。即對於必須打開的對話框的示例,代碼可能如下所示,在相關組件中;
openModal(){
if(this.props.tourStep == 'prompt_modal_open'){
ActionCreator.progressTourStep();
}
// code for actually opening the modal goes here
},
someOtherAction(){
if(this.props.tourStep == 'prompt_modal_open'){
//Display error message here
} else {
//normal action result here
}
}
當用戶沒有參加導遊,只需在減速設定tourStep
到undefined
,任何旅遊相關的功能將被關閉。或者,如果您希望保持組件清潔且「啞巴」,則可以藉助Redux-Thunk將此邏輯直接放入動作創建器中;或者,如果您希望保持組件清潔且「啞」
ActionCreator.openModal = function(){
return function(dispatch, getState){
var state = getState();
if(state.tourStep == 'prompt_modal_open'){
dispatch({type: 'progress_tour_step'});
}
dispatch({type: 'open_modal'});
}
}
ActionCreator.someOtherAction = function(){
return function(dispatch, getState){
var state = getState();
if(state.tourStep != undefined){
dispatch({type: 'show_error'});
} else {
dispatch({type: 'some_other_action_type'});
}
}
}
那麼[自定義元素](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Custom_Elements)呢? – Oriol
對於這個任務的範圍,我只考慮預先存在的html元素,假設「自定義元素」是指元素添加到HTMLElement.prototype? – user3457884
也許劫持像'insertBefore','appendChild','removeChild'等DOM方法...... – Oriol