Help us understand the problem. What is going on with this article?

backbone.stickit の select がうまくバインドされないとき

More than 3 years have passed since last update.

backbone.stickit で、<select>に数値型の値をバインドさせようとすると、単純にはうまくいきません。

具体的には、テンプレートが

<select id="category">
  <option value="1">カテゴリ1</option>
  <option value="2">カテゴリ2</option>
</select>

で、JavaScript が

var Model = Backbone.Model.extend({
  defaults: {
    categoryId: 2
  }
});

var View = Backbone.View.extend({
  el: document,

  bindings: {
    '#category': 'categoryId'
  },

  render: function() {
    this.stickit();
    return this;
  }
});

$(function() {
  var model = new Model();
  var view = new View({ model: model });
  view.render();
});

のようなとき、カテゴリ2 が選択されません。
categoryId が、文字列の "2" ならばバインドされますが、属性の型は変えたくない場合が多いと思います。

対処

<option>data-stickit-bind-val 属性を追加することで解決します。

<select id="category">
  <option value="1" data-stickit-bind-val="1">カテゴリ1</option>
  <option value="2" data-stickit-bind-val="2">カテゴリ2</option>
</select>

value の値と同じですが、data-stickit-bind-val は型変換されるので、数値を書いておくと数値型としてバインドされるようになります。

milk1000cc
ウェブサービスを作っています https://ponpon.in/ https://furufuru.tv/
https://milk1000.cc/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした