Backboneでインスタンスごとに設定を変えたい
var Index = Backbone.Model.extends({ defaults: function () { return { index: 0 } }, max:0, min:0, next: function () { var index = this.get("index"); index = Math.min(Math.max(index + 1, this.min), this.max); this.set("index", index); }, prev: function () { var index = this.get("index"); index = Math.min(Math.max(index - 1, this.min), this.max); this.set("index", index); } });
var index = new Index({ index:3 }); index.min = 0; index.max = 100;
こういう感じでModelとして管理したい値と、Modelの操作に設定として使いたい値があるとします。
その設定をインスタンスごとに渡す方法がわからなくて強引にプロパティを設定したり、変更しないattributesを使ってどうにかしていたけど、第二引数のoptionsとして渡してあげると Model#initializeにそのまま渡されるのでそこで設定すればよいみたい。
var Index = Backbone.Model.extends({ defaults: function () { return { index: 0 } }, max:0, min:0, initialize: function (attr, options) { options || (options = {}); this.max = options.max || 0; this.min = options.min || 0; }, next: function () { var index = this.get("index"); index = Math.min(Math.max(index + 1, this.min), this.max); this.set("index", index); }, prev: function () { var index = this.get("index"); index = Math.min(Math.max(index - 1, this.min), this.max); this.set("index", index); } });
var index = new Index({index: 3}, {max:100, min:0});
またViewでも、model、elといったデフォルトのプロパティ以外にインスタンスごとに値を設定したいことがあります。
それも同じようにインスタンス化するときの引数に渡すObjectがoptionsとしてView#initializeに渡されるようなので、そちらで値をセットするように書けば設定ができます。
var SlideView = Backbone.View.extends({ $slides initialize: function (options) { options || (options = {}); this.slides = this.$(options.slideClass); this.model.on("change:index", this.render, this); this.render(); }, render: function () { this.$slides.removeClass("current"); this.$slides.eq( this.model.get("index") ).addClass("current"); } });
var index = new Index({index: $("ul#slideshow li.current").index()}, {max:$("ul#slideshow li").length, min:0}); var slideshow = new SlideView({ model: index, el: "ul#slideshow", slideClass: "li" });
<ul id="slideshow"> <li class="current">Page1</li> <li>Page2</li> <li>Page3</li> <li>Page4</li> <li>Page5</li> </ul>
追記
intializeの呼び出しは
this.initialzie.apply(this, arguments);
という感じでコンストラクタに投げられた引数を丸投げされるので、optionsがnullでもエラーにならないように注意する必要があるですね。
options || (options = {}); //optionsが無かったら空のObjetを代入する