-1

How could I implement high-quality routines (mentioned by Steve McConnell, on Code Complete, chapter 7) on some Javascript code? For example, in this case:

$('#variable').on('click', function(){
                          //do some stuff
});

This is a very common snippet, but it is passing a function as parameter to another function. In my point of view, are not self-documented (it is not readable) and does not maintain the program abstraction as the book indicates; but is very commmon to see.

4

2 回答 2

2

您可以将要传递的函数分配给局部变量,因此至少可以给它一个名称:

var onClickCallback = function() {
                      //do some stuff
};

$('#variable').on('click', onClickCallback);
于 2015-01-27T19:41:49.443 回答
-2

假设 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.  
});
于 2015-01-27T21:59:02.123 回答