问题
In a SPA,I have a view in which I include another view using the compose binding. This sub view (child view) has an activate method which is called when the parent view is loaded.
<div data-bind="compose: 'viewmodel/fol/index'"></div>
However, when I navigate away from the parent view and then go back to it (without refreshing the browser), the activate method in the child view is not longer called. How can I force this to be called each time the parent view is loaded?
回答1:
Since you are not leveraging the router here, the behavior of the child viewModel will not respect the full activation lifecycle. There are two approaches you can take: (a) leverage the router or (b) manually activate the child.
If you wanted to take the first approach, you would create a child router on the viewModel and create a router
binding instead of a compose
binding. That might be overkill in this case so I will skip it.
The better approach, given the information you've provided here, would be to not try to hook into the activation lifecycle automatically. So instead of calling your activate()
function activate, call it init()
:
function folIndexViewModel() {
this.init = function() {
...
};
}
In your parent, have your activate function call init
var child = require('viewmodel/fol/index');
function parentViewModel() {
this.activate = function() {
child.init();
}
}
Note that this approach only works if your child is a singleton. More information on that at the bottom of this article: http://durandaljs.com/documentation/Creating-A-Module.html.
来源:https://stackoverflow.com/questions/29829429/durandal-compose-activate-method-not-always-called