以前作って、最近は必ず使っているやつです。
こういうのをractive.extendで設定しておくと共通の機能として使えます。
この場合テンプレートにベタ書きですが、Componentsでつくるやり方もあると思います。
Ractiveテンプレート
Bootstrapのcssを読み込み、Bootstrapのalertをこんなかんじで書く(.alert-wrapでくるんでいます)
閉じるボタンにon-click="alert_hide"
を設定
※ bootstrap.jsは不要
text/ractive
{{#alert}}
<div class="alert-wrap">
<div class="alert alert-{{status}}">
<button type="button" class="close" on-click="alert_hide">×</button>
{{#title}}<strong>{{title}}</strong>{{/}} {{#text}}{{text}}{{/}}
</div>
</div>
{{/alert}}
トランジションのプラグインを使って、
<div class="alert-wrap">
に intro-outro="slide"
やintro-outro="fade"
を仕込むと楽しいです。
イベント登録
ractiveオブジェクト生成は省略
ractive.on({
alert: function (title, text, status, hideAfter) {
//alertにデータが入ると自発的に現れる
this.set('alert', {
title: title || null,
text: text || null,
status: status || 'info',//デフォルトでalert-info
hideAfter: hideAfter || null //デフォルトではタイマーなし
});
},
alert_hide: function (event) {
event.original.preventDefault();
this.set('alert', null);//alertをnullにするだけ これで自発的に消える
}
});
observeでタイマーをセット
タイマー機能がいらなければ、alert.hideAfterのデータと、このobserveは不要です
ractive.observe('alert.hideAfter', function (val) {
//'alert.hideAfter'に値がセットされたらタイマーをセット
val && setTimeout(function () {
this.set('alert', null);//自発的に消える
}.bind(this), val);
}, {init: false});
alertを出す
//xを押すと消えるalert
ractive.fire('alert','アラートタイトル','アラートテキスト');
//3秒で消えるまたはxを押すと消えるalert
ractive.fire('alert','アラートタイトル','アラートテキスト',null,3000);
//bootstrap的にalert-dangerなalert
ractive.fire('alert','アラートタイトル','アラートテキスト','danger');
//イベントを発火せず直接データをセットしてもいいです。
ractive.set('alert', {
title: 'アラートタイトル',
text: 'アラートテキスト',
status: 'info',
hideAfter: 3000
});
//xを押すと消えるalert
ractive.set('alert', {
title: 'アラートタイトル',
text: 'アラートテキスト',
status: 'info',
});
//このアラートを消す
ractive.set('alert', null});