LoginSignup
2
3

More than 5 years have passed since last update.

knockout.jsでズンドコキヨシ(ドコモ光対応版)

Posted at

ここ一ヶ月ほどの間にたくさんのズンドコシステムが世に出てきましたが、お客様からの「ドコモ光に対応してほしい」というご要望に対応できるズンドコが見つからなかったので自分で作ってみました。

knockout_jsでズンドコキヨシ_-_JSFiddle.png

テキストフィールドの文言を変更すると、実行中でもキヨシ発動後でも変更が即反映されます。

html
<div>
  <input type="text" data-bind="textInput: zun"/>
  <input type="text" data-bind="textInput: doko"/>
  <input type="text" data-bind="textInput: kiyoshi"/>
</div>
<div>
  interval(ms):<input type="text" data-bind="value: interval"/>
</div>
<div>
  <button data-bind="click: start">start</button>
</div>

<div data-bind="foreach: results">
  <span data-bind="text: $data"></span>
</div>

<div class="completed">
  <span data-bind="text: kiyoshi, visible: isCompleted"></span>
</div>
JavaScript
var ZundokoViewModel = function() {
  this.zun = ko.observable("ズン");
  this.doko = ko.observable("ドコ");
  this.kiyoshi = ko.observable("キヨシ!");
  this.pattern = [this.zun, this.zun, this.zun, this.zun, this.doko];
  this.interval = ko.observable(500);
  this.results = ko.observableArray();

  this.start = function() {
    this.results.removeAll();
    this.next();
  };
  this.next = function() {
    this.results.push(Math.random() < 0.5 ? this.zun : this.doko);
    if (!this.isCompleted()) {
      setTimeout(this.next.bind(this), this.interval());
    }
  };
  this.isCompleted = ko.computed(function() {
    var len = this.results().length;
    if (len < this.pattern.length) return false;
    var tails = this.results().slice(len - this.pattern.length);
    for (i = 0; i < this.pattern.length; i++) {
      if (tails[i] != this.pattern[i]) return false;
    }
    return true;
  }, this);
};

var viewModel = new ZundokoViewModel();

ko.applyBindings(viewModel);
  • knockout.jsのデータバインディングを使用しています。
  • テキストフィールドのデータバインディングには'textInput'を使用することで入力を即反映するようにしています。(valueだとEnterを押した時、フォーカスが外れた時にしか反映されません)

    <input type="text" data-bind="textInput: zun"/>
    
  • ランダムに選択したズンドコはobservableArray(resultsプロパティ)に格納しています。
    この際、バインドされた値(this.zun())ではなくobservableオブジェクト(this.zun)を直接格納することで、値の変更が即反映されるようになります。

    this.results.push(Math.random() < 0.5 ? this.zun : this.doko);
    
2
3
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
2
3