This works well用于让子菜单在主视图中工作。
通过将 activate: true 添加到 compose 绑定(bind),我能够使 activate() 函数适用于子菜单 View 模型。但其他生命周期事件并未触发。如何让 canActivate()、canDeactivate() 和 deactivate() 在我的 subview 模型中工作?
请参阅我的帖子顶部的链接以获取源代码。此链接问题的答案包含一个示例,我使用该示例将此功能集成到 Hot Towel 项目中。
最佳答案
看起来 @evan-larsen 构造 inAbout
activator() 的方式阻止了 canDeactivate 和 Deactivate 事件的执行。还不知道为什么。
通过将其转换为使用 system.acquire
,我能够再次触发这些事件。
return system.acquire(convertSplatToModuleId(activationData.splat)).then(function( Sample ) {
App.inAbout(new Sample());
});
这是修改后的 about/index.js。
define(
['durandal/system', 'durandal/viewModel', 'durandal/plugins/router'],
function( system, viewModel, router ) {
var defaultPage = 'aboutUs';
function convertNameToModuleId ( name ) {
return 'deepLinkingExample/areas/about/' + name + '/' + name;
}
function convertSplatToModuleId ( splat ) {
if ( splat && splat.length > 0 ) {
return convertNameToModuleId(splat[0]);
}
return convertNameToModuleId(defaultPage);
}
var App = {
inAbout: viewModel.activator(),
activate: function( activationData ) {
return system.acquire(convertSplatToModuleId(activationData.splat)).then(function( Sample ) {
App.inAbout(new Sample());
});
},
showPage: function( name ) {
return function() {
router.navigateTo('#/about/' + name);
};
},
isPageActive: function( name ) {
var moduleName = convertNameToModuleId(name);
return ko.computed(function() {
return this.inAbout().__moduleId__ === moduleName;
}, this);
}
};
return App;
}
);
上面的代码假设您返回的详细虚拟机是构造函数。像下面这样的 aboutMe.js 应该可以做到这一点。
define(['durandal/app', 'durandal/system'], function (app, system) {
var ctor = function() {
this.name = "About me";
this.description = "For demonstration only";
};
ctor.prototype.canActivate = function () {
return app.showMessage('Do you want to view ' + this.name + '?', 'Master Detail', ['Yes', 'No']);
};
ctor.prototype.activate = function() {
system.log('Model Activating', this);
};
ctor.prototype.canDeactivate = function () {
return app.showMessage('Do you want to leave ' + this.name + '?', 'Master Detail', ['Yes', 'No']);
};
ctor.prototype.deactivate = function () {
system.log('Model Deactivating', this);
};
return ctor;
});
关于knockout.js - Durandal 子路由 (Hottowel) 生命周期回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469641/