我正在考虑构建一个 knockout 路由引擎,它根据网址参数按需加载 knockout “组件”,而不是像 99 中那样匹配预定义的路由值示例的百分比。 我需要这个的原因是我将根据条件拥有不同数量的 View 和组件。
对于组件,任务很简单,我只需遵循一些示例,以下内容对我来说效果很好:
ko.components.loaders.push({
getConfig: function(name, callback) {
var componentPieces,
componentName,
componentNamespace
if( name && name.indexOf('-') >= 1){
componentPieces = name.split('-');
componentName = componentPieces[1];
componentNamespace = componentPieces[0];
callback({
viewModel: {
require: "components/" + componentNamespace + "/" + componentName + "ViewModel"
},
template: {
require: "text!components/" + componentNamespace + "/" + componentName + ".tmpl.html"
}
})
}else{
callback(null);
}
},
//use the default loaders functionality for loading
loadComponent: ko.components.defaultLoader.loadComponent
});
到目前为止一切顺利,但我在路由引擎方面遇到了困难,我正在寻找解决方案。 目前这个看起来很有希望,但我有点不觉得
define(["knockout", "crossroads", "hasher"], function(ko, crossroads, hasher) {
var routerConfig = {
defaultParams: { page: 'home', action: 'view' }
};
function Router(config) {
var self = this;
var currentRoute = self.currentRoute = ko.observable({});
crossroads.addRoute(':page:/:action:', function(requestParams) {
var routeParams = $.extend(config.defaultParams, requestParams);
self.currentRoute(routeParams);
});
crossroads.bypassed.add(function(){
self.error(404);
});
self.error = function(code){
self.currentRoute({ page: 'error', code: code });
};
startCrossroads();
}
function startCrossroads() {
function parseHash(newHash, oldHash) { crossroads.parse(newHash); }
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
// crossroads.shouldTypecast = true;
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
}
return new Router(routerConfig);
});
任何有用的资源和IDE将不胜感激。
最佳答案
在这里查看我的博客文章
http://andersmalmgren.com/2014/08/11/single-page-application-with-sub-routing/
它有一个供 View 模型加载的主 ID #MyMainModel
然后它还使用哈希后的查询来监听子路由
#MyMainModel?id=5
我真的不能说它是否是适合您的用例的 100% 解决方案,但也许它可以给您一些指导?
关于javascript - 路由组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25408116/