LoginSignup
6
6

More than 5 years have passed since last update.

Ractive.js + Twitter Bootstrap で自発的に出て自発的に消えるアラート

Last updated at Posted at 2015-03-02

以前作って、最近は必ず使っているやつです。
こういうのを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">&times;</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});

サンプル

jsFiddleにサンプルあげました

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6