简体   繁体   中英

Framework 7 Vue how to stop Firebase from listening to changes when on different pages?

Suppose I have pageA where I listen for a firebase document changes

export default {
  mounted() {
    this.$f7ready(() => {
      this.userChanges();
    })
  },
  methods: {
    userChanges() {
      Firebase.database().ref('users/1').on('value', (resp) => {
        console.log('use data has changed');
      });
    }
  }
}

Then I go to pageB using this..$f7.views.current.router.navigate('/pageB/')

If on pageB I make changes to the /users/1 firebase route I see this ,message in the console: use data has changed , even though I'm on a different page.

Any way to avoid this behavior, maybe unload the page somehow?

I tried to stop the listener before navigating away from pageA using Firebase.off() but that seems to break a few other things.

Are you properly removing the listener for that specific database reference? You'll have to save the referenced path on a dedicated variable to do so:

let userRef
export default {
    mounted() {
        this.$f7ready(() => {
            this.userChanges();
        })
    },
    methods: {
        userChanges() {
            userRef = Firebase.database().ref('users/1')
            userRef.on('value', (resp) => {
                console.log('use data has changed');
            });
        },
        detachListener() {
            userRef.off('value')
        }
    }
}

That way you only detach the listener for that specific reference. Calling it on the parent, would remove all listeners as the documentation specifies:

You can remove a single listener by passing it as a parameter to off(). Calling off() on the location with no arguments removes all listeners at that location.

More on that topic here: https://firebase.google.com/docs/database/web/read-and-write#detach_listeners

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM