IK.AM

@making's tech note


POJO(Plain Old JavaScript Object)なドメインモデルクラスを作成する

🗃 {Programming/JavaScript/POJO}
🗓 Updated at 2014-03-18T01:44:23Z  🗓 Created at 2014-03-18T01:44:23Z   🌎 English Page

Backbone.jsだとBackbone.Modelがあって、var Account = Backbone.Model.extend({/* ... */})な感じでモデルを定義していたけど、Angular.jsではModelを実装するための特別な機構はないので適当にjavascript objectを使う。

Modelにはドメインロジックを書いて、別クラスにしたいってとき、以下のようにすると良い感じ。underscore.jsは使う。元ネタはこちら

function Transaction(attrs) {
  _.extend(this, attrs);
}

_.extend(Transaction.prototype, {
  isDebit: function(){
    return this.amount > 0;
  },

  isCredit: function(){
    return this.amount < 0;
  }
});

function Account(attrs){
  _.extend(this, attrs);
}

_.extend(Account.prototype, {
  addTransaction: function(transaction){
    this.transactions.push(transaction);
  }
});

使用例

var account = new Account({
  number: '87654321',
  transactions: [
    new Transaction({id: 1, amount: 10})
  ]
});

account.addTransaction(new Transaction({id: 2, amount: -5}));

POJOなのでBackbone.Model.toJSON()のようなものは不要で、そのままJSONにできる。

JSON.stringify(account)の結果は"{"number":"87654321","transactions":[{"id":1,"amount":10},{"id":2,"amount":-5}]}"である。

Framework非依存で使用できていい感じですね。


✒️️ Edit  ⏰ History  🗑 Delete