1
1

More than 5 years have passed since last update.

View.attributesを取得・設定するメソッド

Posted at

View.attributesがよく分からなかったので、下記のようなattr()メソッドを作ってました。

var HogeView = Backbone.View.extend({
  attributes: {
    foo: 0
  },
  attr: function(key, val){
    if(val == null){ return this.attributes[key]; }
    this.attributes[key] = val;
  }
});

var hoge = new HogeView();
hoge.attr('foo', 10);
hoge.attr('foo'); // 10

datasetの絡みだったので、$(elm).data()でもよかったのかもしれなかったですが。
でも取得は出来ても、設定は$(elm).attr()じゃないとダメっぽかったので。

{
  attr: function(key, val){
    if(!this.attributes.hasOwnProperty(key)){
      throw new Error('HogeView not has ' + key + ' attribute!');
    }
    if(val == null){ return this.attributes[key]; }
    this.attributes[key] = val;
  }
}

こうしてやると、View.attributesにない項目は取得もできないし設定もできなくなりますね。

1
1
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
1
1