我正在改造一个基于淘汰制的网络应用程序,它将有不同的主题。主题之间的差异可以在视图中,也可以在功能中。某些功能是特定于主题的,而其他功能可以在2个或更多主题中通用,但不是全部。不过,其他功能可以是所有的主题。
目标是拥有一个框架,通过删除代码复制、具有适当的结构、松散限制的功能和改进的可测试性来提供可维护性。
我正在设想包含可重用功能的组件。我称它们为“基本”组件。这些组件可以通过配置参数进行配置。这些组件并不是特定于任何主题的。
我要制定一个框架,允许:
为了实现上述要求,我使用了Knockout 3.2+中提供的3.2+支持。
我已经能够处理特定于主题的视图,但无法找到扩展主题中的“基本”组件的方法。
任何关于这方面的想法都是受欢迎的。
我创建了两个KO组件:“基本菜单”和“菜单”。
“基本菜单”组件是:
define("base-menu", ['knockout'], function (ko) {
function ViewModel(params) {
// this parameter should be configurable in theme
var name = params.name || "No Name";
this.name = ko.observable(name);
this.dispose = function () {
console.log("base dispose");
}
};
return {
viewModel: ViewModel,
template: '<h2><span data-bind="text: name"></span> Settings in BASE</h2>'
};
});“菜单”部分是:
// TODO: this component should "inherit" from base-menu, so that it has a "name" observable
define("menu", ['knockout'], function (ko) {
function ViewModel(params) {
this.sections = params.sections || [];
this.selectedSection = ko.observable();
this.dispose = function () {
// TODO: this should call base-menu's dispose function
console.log("theme dispose");
}
};
return {
viewModel: ViewModel,
template: '<h2><span data-bind="text: name"></span> Settings in THEME</h2><ul class="nav nav-pills" data-bind="foreach: sections"><li data-bind="css: { active: $parent.selectedSection() === $data }"><a href="#" data-bind="text: $data, click: $parent.selectedSection"></a></li></ul>'
};
});“菜单”组件应该从“基本菜单”组件“继承”,以便它有一个可观察到的“名称”。
我怎样才能做到这一点?
在JSFiddle上给出了可编辑的例子
发布于 2015-09-29 11:27:04
您可以通过使用原型继承来实现这一点--尽管它有点难看,特别是没有super概念来调用基本方法。您可能会考虑通过Babel使用ES2015和transpile,从而获得更清晰的类语法。
// TODO: this component should "inherit" from base-menu, so that it has a "name" observable
define("menu", ['knockout', 'base-menu'], function (ko, baseMenu) {
function ViewModel(params) {
baseMenu.viewModel.call(this, params);
this.sections = params.sections || [];
this.selectedSection = ko.observable();
this.dispose = function () {
baseMenu.viewModel.prototype.dispose.call(this);
// TODO: this should call base-menu's dispose function
console.log("theme dispose");
}
};
ViewModel.prototype = new baseMenu.viewModel();
return {
viewModel: ViewModel,
template: '<h2><span data-bind="text: name"></span> Settings in THEME</h2><ul class="nav nav-pills" data-bind="foreach: sections"><li data-bind="css: { active: $parent.selectedSection() === $data }"><a href="#" data-bind="text: $data, click: $parent.selectedSection"></a></li></ul>'
};
});// menu.{js|ts|es6}
// Same thing in ES2015/ES6/TypeScript
import ko, { observable } from 'knockout;
import { viewModel as BaseMenu } from 'base-menu';
export class viewModel extends BaseMenu {
constructor(params) {
super(params);
this.sections = params.sections || [];
this.selectedSection = observable();
}
dispose() {
super.dispose();
}
};
export var template = 'Your template here';https://stackoverflow.com/questions/32837142
复制相似问题