複数フィールドのchange系イベントハンドラを美しく書く

https://qiita.com/the_red/items/ea2fa351c4d52d43fede

こんなQiita記事書いたので、リンク&一部転載でーす。

 

複数フィールドでchange系のイベントハンドラを使う際、こんな風にダラダラ長くなりがちですよね。

kintone.events.on(['app.record.create.show','app.record.edit.show','app.record.index.edit.show','app.record.create.change.first\_name','app.record.create.change.last\_name','app.record.create.change.full\_name','app.record.edit.change.first\_name','app.record.edit.change.last\_name','app.record.edit.change.full\_name','app.record.index.edit.change.first\_name','app.record.index.edit.change.last\_name','app.record.index.edit.change.full\_name',],event=\>{// ...})

 

それが、reduce使うとこんなに美しくなります!

const FIELDS = ['first_name', 'last_name', 'full_name']
const EVENTS = FIELDS.reduce(
(events, field) => [
...events,
`app.record.create.change.${field}`,
`app.record.edit.change.${field}`,
`app.record.index.edit.change.${field}`,
],
['app.record.create.show', 'app.record.edit.show', 'app.record.index.edit.show']
)
kintone.events.on(EVENTS, event => {
// ...
})

 

僕は美しいと思うのですが、どうでしょうか・・・?

中級者以上のみなさん、Array#reduce()をどんどん使っていきましょう!

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 

Qiita記事内ではさらに「krewSheet JavaScript APIとのロジック共通化」

も考慮したサンプルコード書いておりますので、よかったら読んでみてください〜。

美しい。

ありがとうございます(//∇//)