はじめに
Hubotを使ってSlackのbotを作ろうと思って、
既存のクラスを使いまわしたいなーと思った時にハマったのでメモ
いろんなサイトを見ていると、window.Hoge
のようにwindowオブジェクトのプロパティにしてしまえとか、@Hoge
としてしまえという話が多かった。
だがしかし、Hubotには画面がないからwindowオブジェクトなんてないし、
@が使えるのも画面を管理するview側からだけ。
解決策
ひとことで言うと、呼ばれる側のクラスclass Hoge
のmodule.exports = (robot)
の中で、module.exports = Hoge
としてあげればいい。
そして呼び出す側は、Hoge = require('./hoge')
としてあげれば自由に使うことができる。
ソースコード
シンプルに書くと以下の様な感じ。
hoge.coffee
class Hoge
constructor: (@robot) ->
module.exports = (robot) ->
hoge = new Hoge robot
robot.hear /hogehoge/i, (msg) ->
msg.send "hogehoge"
module.exports = Hoge
で、呼び出す側では
fuga.coffee
Hoge = require('./hoge')
module.exports = (robot) ->
hoge = new Hoge robot
のようにする。
ちなみに
hoge.coffee
をjsに変換してみると以下のようになる。
hoge.js
var Hoge;
Hoge = (function() {
function Hoge(robot1) {
this.robot = robot1;
}
return Hoge;
})();
module.exports = function(robot) {
var hoge;
hoge = new Hoge(robot);
robot.hear(/hogehoge/i, function(msg) {
return msg.send("hogehoge");
});
return module.exports = Hoge;
};