Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listening to browser events from the Vuex store

I would like to provide Gamepad support for my Vue app. I would like to listen to the events from the Gamepad API.

I don't want to attach those listeners to a component because I have to deal with them globally. So where should I attach those listeners? Should I add each event to the App.vue component, because it's the root of the app?

I want to handle the gamepad inputs and states with Vuex. Is there a way I can listen directly to browser events via actions (/or mutations)? It would be awesome to setup my actions like...

export default {
  on_browser_gamepadconnected: ({ commit }, e) => {
    // do something
  },
};
like image 295
Question3r Avatar asked Nov 26 '19 19:11

Question3r


1 Answers

Make your own Vuex plugin

https://vuex.vuejs.org/guide/plugins.html

Your basic Vuex store will look like this.

const state = {
  humans_gone: false
}

const getters = {

}

const mutations = {
  markAsDestroyed(state, value){
     state.humans_gone = value
  }
}

const actions = {
  async destroyAllHumans({ commit, dispatch, state }, exceptMyFriends) {
    // Do stuff
  }
}

const plugins = [
  store => {
    window.addEventListener("gamepadconnected", async e => {
      await store.dispatch('destroyAllHumans', true)
      store.commit('markAsDestroyed', true)
      console.log(`If this is ${store.state.humans_gone}, then I am all done`)
    })
  }
]

export default {
  state,
  getters,
  mutations,
  actions,
  plugins
}
like image 160
Trevor Avatar answered Nov 13 '22 11:11

Trevor