Dojo - 如何在没有继承的情况下覆盖所有实例的方法?

时间:2012-06-11 14:33:06

标签: dojo dijit.form

我正在尝试扩展现有的dijit.form.Button以接受“topic”属性并在onClick上发布该命令/主题。我提出的解决方案需要引用前一个Button.prototype_onClick方法。有没有更好的方法来编码,所以下面的用法示例仍然有效?

define(["dojo/_base/lang", "dijit/form/Button"], function(lang, Button) {
    var oldClick = Button.prototype._onClick;
    lang.extend(Button, {
        topic: null,
        _onClick: function(e) {
            alert('test');
            if (this.topic) {
                connect.publish(this.topic);
            }
            return oldClick.apply(this, arguments);
        }
    });
});

用法:

<button dojo-data-type="dijit.form.Button" data-dojo-props="topic: 'test'">Test</button>

require(["dojo/_base/connect"], function(connect) {
    connect.subscribe("test", function() {
        alert("you just clicked the test button");
    });
});​​

1 个答案:

答案 0 :(得分:4)

考虑Aspect-oriented programming,即dojo/aspect

require([
    "dojo/aspect",
    "dojo/topic",
    "dijit/form/Button"
], function(
    aspect,
    topic,
    Button
) {

    aspect.after(Button.prototype, "_onClick", function(e) {
        this.topic && topic.publish(this.topic);
    });

    topic.subscribe("test", function() {
        console.log("test topic");         
    });

});​

查看实际操作:http://jsfiddle.net/phusick/2rjfJ/