Search code examples
coffeescriptderbyjs

Unsubscribe on page change


I'm working on a Derby application and can't seem to figure out how to unsubscribe on page leave. I know how to unsubscribe in general, but hooking the page leave seems to be the problem.

My existing code looks very similar to:

get "/somePath", (page, model) ->
    someQueryHere = model.query("somecollection").someMotif()

    model.subscribe someQueryHere, (err, results) ->
        if err?
            ...
            return

        ...

    do page.render

Solution

  • What do you mean by 'on page leave' exactly? Unsubscribing is not necessary when a full page reload happens, the socket.io connection would be terminated anyway.

    On the other hand if you want to unsubscribe from models on a client side page render, you could try using one of the render events:

    app.on 'pre:render', ->
      model.unsubscribe someQueryHere
    

    Note, that render events happen after the route have been executed so you should pay attention not to unsubscribe from a query/path you just subscribed to.

    Anyway, a more complete example would help to better understand your question.

    Another note regarding your example: page.render() should be probably called inside the subscribe callback. Also, why do you use do page.render instead of simply calling it like this: page.render()?