ui-router: Do controllers ever get destroyed after transitions? - angularjs

I am using ui-router and am trying to detect when a controller belonging to a view that's being transitioned away from gets destroyed.
So I currently have a destroy listener like so:
$scope.$on('destroy', function(){
mySpecialFunction();
});
However, when a state change occurs to a different view\controller, this destroy event never fires.
The state I am transitioning to, is a sibling state so I'm going from myParent.childA to myParent.childB (where childA has the destroy listener added).
If I was instead going from myParent.childA to myParent.childA.child1 then this would make sense since childA still exists in the hierarchy.
Can someone help me understand why the scope still exists in this scenario please?

The event name you want is "$destroy" not "destroy"
Try
$scope.$on('$destroy', function(){
mySpecialFunction();
});
This should get triggered under the conditions mentioned in question

Related

Is there a direct way to know to which view I am going in ionic?

I have an interval running that I want to leave active if the user goes to a specific view.
Is there a way to check this in $scope.$on('$ionicView.beforeLeave') or similar?
You can use the $stateChangeStart event, which is triggered when users navigate to another state and gives you the next state, so you can find the view you are going to. Also, you can check the current state if it's a matter or stop the state navigation by stopping the event default (i.e. event.preventDefault();). So then, you can enable yout $interval within the event handler or disable as well.
$rootScope.$on('$stateChangeStart',
function (event, nextState, nextParams, currentState, currentParams) {
// use the nextState to handle this
// and use event.proventDefault() to stop the state change
});

$stateChangeSuccess getting hit twice

I have an $http call that is made inside of a function getRoutes that fires off whenever that state has changed:
$scope.$on('$stateChangeSuccess', function(event) {
$scope.getRoutes($stateParams);
})
I have another function that changes a state parameter and then calls $state.go():
$scope.bindSelectedRoute = function(){
$stateParams.pickup_route= this.d.pickup_route;
$state.go('track.search', $stateParams);
}
My problem is that the http call keeps being made twice. First with the $stateParams correct and then a second call with an empty object getting passed. I'm assuming this is a core part of angular that I'm missing.
Any hints?
Best.
I can't suggest refactored code for you but I believe the answer is because you did a $state.go(). You already told the app to fire $scope.getRoutes($stateParams) when the stateChangeSuccess is fired so when $state.go() fires and it successfully changes the state, $scope.getRoutes($stateParams) gets fired again.

Prevent all $state transitions until promise is resolved

I am using ui-router.
I want to be able to block any state transitions until a promise is resolved.
There's are multiple states, so setting the same resolve property on all is not a good idea.
The promise needs to be resolved inside the Angular app, so bootstrapping the app after an external promise is resolved won't work.
My current solution relies on having a $stateChangeStart listener that calls event.preventDefault(); and which removes itself after the promise is resolved. There are many complications with this solution besides the fact that its intention isn't clear unless well commented.
So, is there a better solution to block all state transitions until everything's cool?
Create one abstract parent state, make the rest children of that state. Use the resolve object on the parent state so it's resulting dependency will be available to all child states.
See: https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#abstract-states
An abstract state can have child states but can not get activated itself. An 'abstract' state is simply a state that can't be transitioned to. It is activated implicitly when one of its descendants are activated.
Some examples of how you might use an abstract state are:
To provide resolved dependencies via resolve for use by child states.
I think you want to use $urlRouterProvider.deferIntercept()
See here: http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.$urlRouterProvider
app.config(function ($urlRouterProvider) {
$urlRouterProvider.deferIntercept();
};
app.run(function($urlRouter, myservice) {
myservice.promise.then(function() {
$urlRouter.listen();
$urlRouter.sync(); // not sure if this is necessary
});
});

Should all Backbone on/off events be replaced with listenTo/stopListening?

As far as I have been able to tell, listenTo and stopListening should replace on and off respectively. Do I understand that correctly? Is there any situation where on/off should be used instead of listenTo/stopListening?
Edit:
As I went to refactor my code, it became obvious that there are some cases for on over listenTo. The documentation is pretty clear that it is for when one object listens to another object:
Tell an object to listen to a particular event on an other object.
Therefore, when a collection or model is listening to an event on itself, we should use on instead of listenTo.
Assuming I have this correct...
The simple rule to follow is this:
Use listenTo when listening for events on another object. Use on when listening to events on self.
Copying an extract from an interesting blog post that I read recently. Hope it helps.
Avoiding common backbone pitfalls: Creating memory leaks by not unbinding events
A common pattern in Backbone.js is creating views that listen on changes in models or collections. This technique is usually intended to allow the view to automatically re-render itself when the underlying data changes. It also means that for large collections we may end up with many views (at least one for every model in the collection) that we may dynamically create or destroy based on changes to the data.
The problem arises when we remove a view (usually by calling its .remove() method), but forgetting to unbind the methods that listen on model changes. In such a case, even though our code may no longer hold a reference to that view, it is never garbage collected since the model still holds such a reference via the event handler.
Take this view for example:
var SomeModelView = Backbone.View.extend({
initialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
// render a template
}
});
When calling the .remove() method, the "change" event handler (our render function) is still bound. So while the DOM element may be removed, the view object itself is never released from memory.
Solving this is easy (especially since Backbone 0.9.x) - all we need to do is to stop using .on() when binding the event handler. instead, we can use the new .listenTo() method, like this:
initialize: function() {
this.listenTo(this.model, 'change', this.render);
}
The biggest difference here being the shift in responsibility from the model to the view. This means that whenever we call .remove(), the view will automatically unbind any event bound to it using the .listenTo() method, essentially fixing this common leak.
For the most part, you understand it correctly. Here is a discussion on the matter from their github repository: https://github.com/documentcloud/backbone/issues/1923#issuecomment-11462852
listenTo and stopListening keep track of state. It will take care of cleanup for you at the cost of a little code overhead. In just about every case I can think of you'd want this behavior for your views, but you wouldn't be at fault for handling on/off calls yourself either; they won't be deprecating on and off any time soon.

Don't call render() if the View itself updated Model via Backbone.Model.set()

In my Backbone.js project I have one Model and several Views. All Views have registered callbacks for 'change:currentTextTitle' on this model:
// 'this' stands for any of the Views here
myModel.on('change:currentTextTitle', this.render, this);
Now a user performs some action, which causes the specific View to change its "current text title" field. This specific view then calls myModel.set("currentTextField", newTextValue) which in turn triggers the 'change:currentTextTitle' event calling all Views (including the one from which set() originated). Then all Views call their render callback functions.
The problem is that the render method is also called on the View from which the set()-Method was originally called, which is completely unnecessary because it is already up-to-date with currentTextTitle.
How would my Views call myModel.set() in a way that the other Views' callbacks get informed, but without triggering/calling the "source View" itself?
One workaround seems to be to pass the source view as part of the options parameter of the set() method (which gets passed along to trigger() and then along the the render() callback):
myModel.set("currentTextField", newTextValue, thisViewSetAttribute)
Then in the render callback one could check if thisViewSetAttribute != this. However, instead of implementing checks in every callback, I think it would make more sense to handle this in the Model itself by only calling the necessary callbacks and ignoring the source View from which the set() method call originated. Is this possible?
I think the 'proper' MCV solution is that your views should not know or care how the model changed, they should simply handle the change and update accordingly. If they are already current, the user shouldn't know the difference.
I definitely would not pass the source view to the model. Instead when the model changes, you could just have the view check if it is current and not re-render. But if the extra render doesn't cause any issues then just let it happen :)
In Backbone, the 'view' is both view and controller. So try to treat the change as 2 separate steps. First, convert user input into changes on the model, then as a separate step (initiated by model change event), handle that change and update the view. If each view does this, no matter how the model changes, everything will stay up-to-date.

Resources