假设 DOM 节点#variable
是调用服务的“小部件”UI 元素的根,并在单击时添加了 CSS 类“单击”。
以下代码演示了单一职责原则、模型-视图-控制器、依赖注入、有意义的命名、良好的文档、无全局变量、数据封装、高内聚、低耦合等:
/**
* Responsible for performing some
* significant action(s) related to
* widgets.
*/
function WidgetService() {}
WidgetService.prototype.doSomething = function() {
//do some stuff
};
/**
* Responsible for wiring up the object
* graph backing the widget.
*/
function WidgetController($, widgetService) {
this._service = widgetService;
this._model = new WidgetModel({
renderCb: renderCb.bind(this)
});
this._view = new WidgetView($, this._model);
this.onClick = this._onClick.bind(this);
function renderCb() {
this._view.render();
}
}
WidgetController.prototype._onClick = function() {
this._service.doSomething();
this._model.isClicked = true;
};
/**
* Responsible for encapsulating the
* state of the UI element.
*/
function WidgetModel(options) {
options = options || {
renderCb: noop
};
this._renderCb = options.renderCb;
}
WidgetModel.prototype = {
_isClicked: false,
get isClicked() {
return this._isClicked;
},
set isClicked(value) {
this._isClicked = value;
this._renderCb(this._isClicked);
}
};
/**
* Responsible for interacting with the DOM.
*/
function WidgetView($, model) {
this._$ = $;
this._model = model;
this.render = this._render.bind(this);
}
WidgetView.prototype.el = '#variable';
WidgetView.prototype._render = function() {
this._$(this.el).addClass(this._model.isClicked ? 'clicked' : '');
};
/**
* Responsible for linking the DOM
* event with the controller.
*/
function WidgetRouter($, controller) {
$(WidgetView.prototype.el).on('click', controller.onClick);
}
function noop() {}
$(function() {
// Go...
var s, c, r;
s = new WidgetService();
c = new WidgetController($, s);
r = new WidgetRouter($, c);
// Now clicking on the element with ID '#variable' will add a class of clicked to it.
});