--- title: POJO(Plain Old JavaScript Object)なドメインモデルクラスを作成する tags: [] categories: ["Programming", "JavaScript", "POJO"] date: 2014-03-18T01:44:23Z updated: 2014-03-18T01:44:23Z --- Backbone.jsだと`Backbone.Model`があって、`var Account = Backbone.Model.extend({/* ... */})`な感じでモデルを定義していたけど、Angular.jsではModelを実装するための特別な機構はないので適当にjavascript objectを使う。 Modelにはドメインロジックを書いて、別クラスにしたいってとき、以下のようにすると良い感じ。underscore.jsは使う。元ネタは[こちら](http://victorsavkin.com/post/67496301619/building-models-in-backbone-and-angular)。 ```javascript 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); } }); ``` 使用例 ```javascript 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非依存で使用できていい感じですね。