2012-06-11 108 views
0

我想擴展現有的dijit.form.Button來接受'主題'屬性併發布該命令/主題onClick。我提出的解決方案需要引用前面的Button.prototype_onClick方法。有沒有更好的方法來編碼,以便下面的使用示例仍然有效?Dojo - 如何覆蓋沒有繼承的所有實例的方法?

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"); 
    }); 
});​​ 

回答

4

考慮Aspect-oriented programming,即​​:

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/