Deathslice246
How to unbind custom channel events?
At the moment, I’m using angularjs with phoenix and I want to know how can I unbind custom channel events.
In Angularjs, one way would be like this.
var unbindHandler = $scope.$on("channel_event", channelFunction); // returns a deregistration function
.... later down the line
unbindHandler() // event is unbinded
unbindHandler = null
When I try to do the same thing with with the channel object.
var unbindHandler = channel.on("new_message", message => {
... code
})
and call it
unbindHandler()
I get an error saying that unbindHandler is not a function because it is undefined. Because of this I have to assume that channel.on doesn’t return a deregistration function for me to use so I can unbind when I’m done. What can I do?
I’ve tried to leave the channel(channel.leave()) hoping that it would automatically unbind but it still doesn’t.
Marked As Solved
voughtdq
Ah! I know what’s wrong.
It looks like the ref logic is only available in master right now.
You can do this:
function channelFunctionFactory(channel) {
return function(event, callback) {
channel.on(event, callback);
return function() {
channel.off(event);
}
}
}
var channelFunction = channelFunctionFactory(channel);
var unbindHandler = channelFunction("new_message", message => { ... });
unbindHandler();
Unfortunately it means you can’t bind to the same event multiple times. You could also try getting the updated phoenix.js from master.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








