How to get rid of viewmodel in Durandal after deactivation

I use durandal and requirejs to create my view models. I also connect to the deactivate lifecycle callback method every time I move from view. I want to get rid of my view model in this method.

I tried delete this , this = undefined , but they don't seem to work.

I also use the durandal event aggregator as follows:

 self.activate = () => { App.trigger("testEvent"); }; App.on("testEvent").then(() => { alert('Event Triggered!'); }); 

Thus, every time a view model is loaded, an event is fired. Now, if I go from the view, then go back (hence, the view model will be loaded again), then the event will fire twice. If I go to view the third time, the event will be fired 3 times, etc. Etc. Thus, previous view modes are still present, so the durandal event is fired by each view model. Therefore, to fix this problem, I need to turn off the view modes when deactivating, how can I do this?

Note. the models in question are temporary, not solitary.

+5
source share
2 answers

Durandal also provides a “hooked” lifecycle hook that only receives triggers if the view is added to the DOM. If you place event subscriptions here, they should only subscribe once.

http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks

EDIT:

As for canceling events, if you save the return value from the subscription, which you can call .off later in deactivated or unchecked methods

 var subscription = App.on("testEvent"); ... subscription.off(); 

http://durandaljs.com/documentation/Leveraging-Publish-Subscribe.html

The view model itself is only a javascript managed object and will be automatically deleted after all links to it disappear.

+2
source

It probably refers to your view model because you are subscribing to the testEvent event, but you are never unsubscribing. I am not an expert on how it will be located in javascript, but have come across similar scripts in .net

Your event will not be triggered three times, it will fire once, but the event handler function will be called for each subscription, so after 3 navigations 3 times.

Try unsubscribing in the deactivation method and see if it works. This will at least stop the event handler trigger. I am not sure if this will display your view model correctly.

+1
source

Source: https://habr.com/ru/post/1262288/


All Articles