|
# I wanted to be able to easily add back button callbacks to certain app states |
|
# (using the word "state" here in the context of ui-router). |
|
# For example, I always know that the back button on page X should quit the app, etc. |
|
# So I wrote this nifty service. |
|
|
|
angular.module("groupmuse").service "BackButtonManager", ($rootScope, $ionicPlatform) -> |
|
managedStates = [] |
|
|
|
$rootScope.$on '$stateChangeSuccess', (event, next) -> |
|
# Disable all listeners |
|
for state in managedStates |
|
if state.enabled |
|
state.unregisterCallback() |
|
state.enabled = false |
|
|
|
# Enable appropriate listener, if any |
|
for state in managedStates |
|
if next.name is state.name and !state.enabled |
|
# registerBackButtonAction returns a function, which when called, disables the callback |
|
state.unregisterCallback = $ionicPlatform.registerBackButtonAction state.callback, 100 |
|
state.enabled = true |
|
break |
|
|
|
return { |
|
attachToState: (state, callback) -> |
|
# Remove any existing managers for this state |
|
managedStates = _.reject managedStates, (s) -> s.name is state |
|
|
|
# Set up an object to manage each state |
|
managedStates.push |
|
name: state |
|
callback: callback |
|
enabled: false |
|
} |
|
|
|
|
|
# That's it, and you can use it like this (while initializing your app): |
|
angular.module("your_app", [ "ionic"]).run (BackButtonManager) -> |
|
BackButtonManager.attachToState 'app.events', -> |
|
navigator.app?.exitApp() or navigator.device?.exitApp() |
|
# Attach to as many states as you want! |
Amazing. Thanks so much.