Ampersand.js所感
ちょっと前に紹介されてたAmpersand.jsを使ってみたので、ざっくりとした紹介。
Ampersand.jsはView, Model, Routerなど複数のモジュールに分割されていて、個別に読み込んで使うことができる。
$ npm i --save ampersand-model
で
var AmpModel = require('ampersand-model');
多くのモジュールはBackbone.jsのコードをベースにしているので、名前が同じものは概ね同じ感覚で使うことができる。
以下、全部ではないけど触ったモジュールのBackboneとの違いをざっくり紹介。
ampersand-state
後述するampersand-model
のベースになるモジュール。違いとしてはAjax周りの機能がない。
get/setメソッドを介さずにプロパティへのアクセスができる
var AmpersandState = require('ampersand-state'); var state = new AmpState(); state.foo = 1; state.foo // => 1
プロパティの型やEnum, nullの許可など詳細な設定
var AppState = AmpersandState.extend({ extraProperties: 'ignore', props: { foo: { type: 'number', default: 0, values: [0, 1, 2] }, bar: { type: 'string', default: 'ampersand', required: true, allowNull: false } } }); var state = new AppState(); state.foo = '1'; // => TypeError: Property 'foo' must be of type number. Tried to set 1 state.foo = 3; // => TypeError: Property 'foo' must be one of values: 0, 1, 2. Tried to set 3 state.bar = null // => TypeError: Property 'bar' must be of type string (cannot be null). Tried to set null
sessions, derived
sessions
は一時的な値を保持するための、derived
は関数を設定できるプロパティ。どちらもtoJSON
で列挙されない。
var AppState = require('ampersand-state').extend({ sessions: { active: { type: 'boolean', default: true } }, derived: { foobar: function() { return this.foo + this.bar; } } }); var state = new AppState(); state.set({foo: 1, bar: 2}); state.foobar; // => 3 state.active = true; state.toJSON(); // => {foo: 1, bar: 2}
ampersand-model
ampersand-state
にモジュールampersand-sync
を追加し、fetch
やsave
を使えるようにしたもの。ajaxConfig
でheaderやbeforeSendの詳細な設定ができたりする。
ampersand-collection
Backbone.Collection
に相当するが、ampersand-sync
およびUnderscore.jsを使用したメソッドは含まれない。(forEachやmapなど、ES5のメソッドは使える)
ampersand-rest-collection
ampersand-collection
にsync
とUnderscore.js関連のメソッドの他、指定したidのモデルがあればそれを返し、なければfetchするfetchOrGet
などが追加されている。
ampersand-view
Backbone.Viewの機能に加えて、2-way-bindings
,collectionView
,subView
など、backbone.stickitやMarionette.jsなどでもおなじみの機能を含む。
ampersand-router
大部分はBackbone.Routerのコードが元になっているが、historyを残さずに遷移するredirectTo
などが追加されている。
CLIツール
コマンドラインから使えるジェネレータもある。
$ ampersand gen model foo
new Model created as client/models/foo.js
new Collection for foo created as client/models/foo-collection.js
ドキュメントは普通に充実しているので、詳細はそちらを見てもらった方が早いです。
http://ampersandjs.com/docs
モジュールは上記以外にも色々ある。
tools.ampersandjs.com
まとめ
感想としてはモジュール化 + 人気のプラグインを取り込んで痒いところに手が届くようになったBackbone.js。モジュールが分散していることもあってgithubのstarはまだ少ないのだけれど、ちゃんとOrganizationがあって活発にメンテされているのも良い。大きなフレームワークを使っていてもプロダクトの要件にバッチリハマるみたいなことはそうそう無くて、結局は複数を組み合わせるとか、ラッパーを書くとかする必要が出てくるので、そうした面でも最初からモジュール化されているのは理にかなっていると思う。
自分は今のところReact.js + Model,CollectionをFluxアーキテクチャで言うところのStoreとして使っていて、他にもVue.jsと組み合わせるとか、純粋にBackbone.jsの上位互換のMVCフレームワークとしてとか、色々使い道はありそうなので試していきたい。