キー入力と同時に文字数をカウントする仕組みが簡単に作れる。
たとえばツイートときに表示されるカウンタの仕組みとかですね。
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/