Javascript: Mixing constructor pattern and Revealing Module Pattern

情到浓时终转凉″ 提交于 2019-12-11 02:08:51

问题


Is there any way I can do have a Javascript class that extends an object that was created through the revealing module pattern? I tried the following code, but is there away to achieve the same thing?

sv.MergeQuestionViewModel = function () {
    this = sv.QuestionDetailViewModal();
    this.init($("#mergeQuestionModel"));
};  

sv.QuestionDetailViewModal = function () {
    var $el,
        self = this,
        _question = ko.observable(),
        _status = new sv.Status();

    var _init = function (el) {
        $el = el;
        $el.modal({
            show: false,
            backdrop: "static"
        });
    };

    var _show = function () {
        $el.modal('show');
    };

    var _render = function (item) {
        _question(new sv.QuestionViewModel(item));
        _show();
    };

    var _reset = function () {
        _question(null);
        _status.clear();
    };

    var _close = function () {
        $el.modal('hide');
        _reset();
    };

    return {
        init: _init,
        show: _show,
        render: _render,
        reset: _reset,
        close: _close
    };
};

回答1:


You could use jQuery.extend to achive this behaviour.

sv.MergeQuestionViewModel = function () {
    $.extend(this, sv.QuestionDetailViewModal);

    this.init($("#mergeQuestionModel"));
};

sv.QuestionDetailViewModal = (function () {
 var el,

 _init = function($el) {
    el = $el;
    console.log('init', el);
 },

 _render = function() {
    console.log('render', el);
 };

 return {
   init : _init,
   render : _render
 };
}());

var view = new sv.MergeQuestionViewModel();
view.render();

Test it on http://jsfiddle.net/GEGNM/



来源:https://stackoverflow.com/questions/13999118/javascript-mixing-constructor-pattern-and-revealing-module-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!