ラッパーのメソッド/変数をDOMオブジェクトにディスパッチしてみる。
forwardable.jsがこんな感じ。
def_delegator = function(self, accessor, method_or_variable, ali) { if(!ali) ali = method_or_variable; var receiver = accessor[method_or_variable]; if(typeof(receiver) == "function") { self[ali] = function() { return receiver.apply(accessor, arguments); }; } else { self["get_" + ali] = function() { return accessor[method_or_variable]; }; self["set_" + ali] = function(v) { accessor[method_or_variable] = v; } } };
こんな感じで使う。
<html> <head> <script type="text/javascript" src="forwardable.js"></script> <script type="text/javascript"> function Text(id) { var element = document.getElementById(id); def_delegator(this, element, "value"); def_delegator(this, element, "onchange"); def_delegator(this, element, "focus"); } function Submit(id) { var element = document.getElementById(id); def_delegator(this, element, "onclick"); } </script> </head> <body> <form onsubmit="return false"> <input id="foo" type="text"><input id="bar" type="submit" value="フォーカス"> </form> <script type="text/javascript"> var text = new Text("foo"); var submit = new Submit("bar"); text.set_onchange(function() { alert("value: " + text.get_value()); }) submit.set_onclick(function() { text.focus(); }); </script> </body> </html>