LoginSignup
3
2

More than 5 years have passed since last update.

[KnockoutJS]キー入力値を即座に取得/反映するには

Last updated at Posted at 2013-12-10

キー入力と同時に文字数をカウントする仕組みが簡単に作れる。
たとえばツイートときに表示されるカウンタの仕組みとかですね。
KnockoutJSだと簡単にできます。

ひな形

<p>テキスト: <input data-bind="value: userName" /></p>
<p>カウンタ: <span data-bind="text: userNameCount"></span></p>
$(function(){

function viewModel() {
    this.userName = ko.observable("入力内容を変えてみて!");
    // computedを利用して文字数を生成
    this.userNameCount = ko.computed({
        read: function () {
            return this.userName().length;
        },
        owner: this
    });
}
ko.applyBindings(new viewModel()); 

});

上記のコードでは、テキスト入力後のフォーカスアウトのタイミングでカウンタに反映されます。
これを即時に反映させる方法もあります。

valueUpdate

<p>テキスト: <input data-bind="value: userName, valueUpdate: 'afterkeydown'" /></p>
<p>カウンタ: <span data-bind="text: userNameCount"></span></p>

inputにvalueUpdate:'afterkeydown'を追加してください。
この状態でテキスト入力を行うと、keydownの直後に変更が反映されて、カウンタもコロコロと変わるようになります。便利ですね。

ついでにvalueUpdateには以下の3種類があります。

  • keyup
  • keypress
  • afterkeydown

それぞれイベントの起こるタイミングが違います。
公式ではafterkeydownを推してるみたいだったので、これを使いました。

computedについて

何気なく使っているcomputedの機能ですが、これがKnockout便利機能のひとつでもあります。
ここではreadだけを用いていますが、write側も実装できます。

this.userNameTrimed = ko.observable("");
this.userName = ko.computed(function(){
  read: function () {
    return this.userNameTrimed();
  },
  write: function (val) {
    // trim済みとして格納
    this.userNameTrimed($.trim(val));
  },
  owner: this
});

computed内で変更された値は、双方向データバインディングによって画面側にも反映されます。
フォーム系の実装時にはvalueUpdateとcomputedにはとても助かりました。

jsFiddle

サンプルはここで動かせます。
http://jsfiddle.net/nantekkotai/L4gSj/

3
2
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
3
2