ンンンパ

ふとしです

移転しました

backbone.js の説明書の写経をした。

その前に、まず「Backbone.js入門 (全22回) - プログラミングならドットインストール」をひととおりみてさわりを学んだ。動画を見ながら聞きながらいっしょにコードを書いていった。

授業と違って待ってくれないのでせわしなかったけど、逆にだらだらしなくてよかった。

なんとなく流れがわかったようなわからなかったような状態になってとりあえず自分でコードを書こうとしたら全然だめだったので、おとなしく説明書を読むことにした。

Backbone.js 日本語リファレンス」を例によって自分の言葉になおしつつ書きうつしながら、説明がわかりにくいところは「Backbone.js」で原本を参照すると簡潔な説明になってたりそれでもわからない場合は livereloadx とともにブラウザで動かしたりした。

あやふやなところはあやふやなまま書いたが、とりあえず backbone.js がなにをしてくれるのかというのがざらりとわかったので、次は「Backbone.js」にのってる Exsamples をみながら実際のコードをさわっていきたい。




super() がないためオーバーライド時には Backbone.Model.prototype.set.apply などとする必要がある。

Event

Collection は内包する Model の全イベントを監視、Model のイベント発火時に同イベントを発火する。

events 単一のイベント名、あるいは半角スペース区切りで複数イベントを指定。

all で全てのイベントが対象。

object.on(events, callback, [context])

events 発火時に実行される callback を登録する。

events 発火時に callback(events, [*args]) で呼ばれる。

object.trigger で発火時に引数を指定できる。

object.off([events], [callback], [context])

events を削除する。

引数省略で全てのイベントの callback を削除する。

object.trigger(events, [*args])

イベントを発火する。

object.once(events, callback, [context])

一度だけ実行される callback を登録する。

object.listenTo(other, events, callback)

other オブジェクトが発火する events に対する callback を登録する。

object.stopListening([other], [event], [callback])

other オブジェクトが発火する events に対する callback を削除する。

引数省略で全てのイベントの callback を削除する。

object.listenToOnce(other, events, callback)

other の events 発火に対して一度だけ実行される callback を登録する。

Event.type 一覧

addmodel, colllection, optionsCollection に Model が追加された。
removemodel, collection, optionsCollection から Model が削除された。
resetcollection, optionsCollection の全体が入れかえられた。
sortcollection, optionsCollection が並びかえなおされた。
changemodel,options Model のいずれかの attribute が変更された。
change:[attribute]model, value, optionsModel の特定の attribute が変更された。
destroymodel, collection, optionsModel が消去された。
requestmodel, xhr, optionsModel か Collection がサーバーリクエストを開始した。
syncmodel, resp, optionsModel か Collection がサーバーと同期に成功した。
errormodel, xhr, options または model, error, optionsModel.save が失敗した。
invalidmodel, error, optionsvalidate に失敗した。
route:[name]params特定の route と一致した。
routerouter, route, paramsいずれかの route と一致した。
alleventName, *argsあらゆるイベントが発火したときに発火する。event の名前を第一引数とする。

Model

Backbone.Model.extend(properties, [classProperties])

Model を継承したクラスを作成する。

propertiesインスタンスプロパティ
classProperties静的プロパティ

new Model([attributes], [options])

Model インスタンスを作成する。

initialize メソッドを設定していた場合実行される。

attributes 作成時、Model にセットされる。

options.parse true にすると、attributes は parse メソッドを通されて set に渡される。

options.collection Collection を渡すと、url メソッドで URL を取得できる。

model.get(attribute)

Model の attribute 値を返す。

model.set(key, value, [options])

  • change

model.set(attributes, [options])

  • change

key、value は文字列で attriubute を設定できる。

attributes は Object リテラルで複数の attribute を設定できる。

options.silenttrue で change イベントを抑制する。

model.escape(attribute)

attribute 値を HTML に影響を与える特殊文字をエスケープした状態で返す。

model.has(attribute)

model に attribute が存在すれば true を返す。(attriubte 値ではない)

model.unset(attriubte, [option])

  • change

model から attribute を消去する。(attribute 値ではない)

options.silent true で change イベントを抑制する。

model.clear([options])

  • change

model から全ての attribute を消去する。(attribute 値ではない)

options.silent true で change イベントを抑制する。

model.attributes

model の attribute が保持されるプロパティ。

直接変更した場合、イベントが発火しない。

model.id

一意の識別子。

set で model.attributes.id をセットした場合、反映される。

model.id を変更した場合、model.attributes.id には反映されない。

model.idAttribute

model.attributes における id 名。変更できる。

model.id は変更されない。

model.cid

自動的に与えられるユニークな識別子。

model.defaults

model の初期値を Object リテラルで定義する。

model.defaults()

model の初期値を Object リテラル を返す関数で定義する。

model.toJSON()

model.attributes を複製した Object を返す。

model.fetch([options])

  • change

model.url() と通信し、取得結果を model.parse() に通し、model.validate() が実行され、問題なければ model.attributes に反映する。

通信開始時に request イベント、HTTP ステータスが正常なら sync イベント、異常なら error イベント、model.attributes に反映する際、変更があれば change イベントを発火する。

options.silenttrue で change イベントを抑制する。

model.save([key, value], [options])

  • change

model.save([attributes], [options])

  • change

まず attributes に対し model.validate() が実行され、失敗すれば false を返す。成功すれば model.attributes に即時反映され、変更があれば change イベントが発火する。

バックエンドにリソースの新規作成、更新を要求する。model.id が設定されていると PUT、されていなければ POST で model.url() と通信を行う。取得結果を model.parse() に通し、model.validate() が実行され、問題なければ model.attributes に反映する。

通信開始時に request イベント、HTTP ステータスが正常なら sync イベント、異常なら error イベント、model.attributes に反映する際、変更があれば change イベントを発火する。

options.silenttrue で change イベントを抑制する。
options.waittrue で引数 attributes の反映をサーバーの応答を待って行う。

model.destroy([options])

  • sync
  • destroy
  • error

model.url() と DELETE メソッドで通信し、リソースの破棄を要求する。

通信開始時に request イベント、HTTP ステータスが正常なら sync イベントと同時に destroy イベントが発火され、Collection に登録されている場合は Collection からも消去される。HTTP ステータスが異常なら error イベントを発火するが destroy イベントは発火しない。

model.id が設定されていれば、結果にかかわらず jqXHR オブジェクトを返す。設定されていなければ false を返す。

options.waittrue で model の消去をサーバーの応答を待って行う。

model.validate(attributes)

model.attributes を操作する直前に呼ばれるメソッド。値を返すと失敗扱いになり、error イベントの callback に渡される引数となる。

options.error error イベントに対する callback を設定する。

model.url()

model の url を返す。

urlRoot が未定義の場合は例外を投げる。

model.id が設定されている場合は model.urlRoot/model.id、されていない場合は model.urlRoot を返す。

Collection に登録されており、なおかつ collection.url が定義されている場合、collection.url/model.id となる。model.id がなければ collection.url。

model.urlRoot が優先される。

model.urlRoot

model.urlRoot()

model.url() で使用される。

model.parse(response, xhr)

model.fetch()、model.save() などで取得した値が attributes に反映する前に通されるメソッド。

model.clone()

model と同じ attributes を持った model を複製し、返す。

model.isNew()

model.id が未定義であれば true を返す。

model.hasChanged([attrinute])

引数なしの場合、model.attributes のいずれかが変更されていれば true を返す。

引数なしの場合、直近に変更されたものが model.attributes.attribute であれば true を返す。

model.changedAttriubtes([attributes])

引数なしの場合、最後に変更された model.attributes.attribute を含む Object を返す。

引数ありの場合、model.attributes に反映され、直近に変更があった model.attributes.attribute を含む Object を返す。

model.previous(attribute)

change イベントの callback の引数 model のみで使用でき、変更前の値を返す。

model.previousAttributes()

change イベントの callback の引数 model のみで使用でき、変更前の値全てを返す。

Collection

Backbone.Collection.extend([properties], [classProperties])

Collection を継承したクラスを作成する。

properties インスタンスプロパティ

classProperties 静的プロパティ

new Collection([models], [options])

コンストラクタ。

models が Object リテラルの場合、collection.model のコンストラクタが呼ばれ Model 化されて格納される。。未定義の場合は Backbone.Model が呼ばれる。Model である場合、そのまま格納される。

options.modelcollenction.model を設定する。
options.comparatorcollection.comparator メソッドを設定する。
options.parsetrue で collection.parse メソッドを実行する。

collection.initialize([models], [options])

コンストラクト時に呼ばれる。引数はそれぞれコンストラクタに渡されたものと同じ。

collection.model

collection に格納する Model クラスを設定する。

コンストラクタや collection.add に Object リテラルを渡すと、このクラスのコンストラクタが呼ばれる。

collection.models

model が格納されるプロパティ。

models に対して underscore メソッドが使用できる。

forEach (each) map (collect) reduce (foldl, inject) reduceRight (foldr) find (detect) filter (select) reject every (all) some (any) contains (include) invoke max min sortBy groupBy sortedIndex shuffle toArray size first (head, take) initial rest (tail) last without indexOf lastIndexOf isEmpty chain

collection.toJSON()

collection.models 内の各 model の attributes を複製した Object を含む Array を返す。

collection.sync(method, collection, [options])

Backbone.sync メソッドを実行する。

collection.add(models, [options])

  • sort
  • add

collection.models に models を追加する。Object リテラルが渡された場合、collection.model で指定されたクラスのコンストラクタが呼ばれる。その際 model.validate に失敗すると例外を投げる。

collection.comparator が設定されている場合ソートされる。その際、sort イベントは発火しない。

追加された model は add イベントを発火する。

options.mergetrue で model.id が同一の model に対し attributes を上書きする。
options.atcollection.models のどこに追加するか index 指定する。
options.silenttrue で add イベントを発火しない。
options.sortfalse でソートしない。

collection.remove(models, [options])

  • remove

collection から model を削除する。model 自体は消去されない。

model は remove イベントを発火する。callback 引数の options.index には、実際の削除実行時の collection.models での index が設定される。

models には Model インスタンスか model.id、id を含む Object を渡す。

options.silenttrue で remove イベントを発火しない。

collection.reset([models], [options])

  • reset

collection.models を空にする。models が指定されている場合、それが collection.models に格納される。reset イベントが発火され、callback 引数 options.previousModels で削除前の collection.models を参照できる。

options.silenttrue で reset イベントを発火しない。

collection.get(id)

id または cid が一致する model を返す。

collection.at(index)

collection.models の index 位置にある model を返す。

collection.push(model, [options])

  • add

collection.models の最後尾に model を追加し、add イベントを発火する。

追加された model も add イベントを発火する。追加された model を返す。

collection.comparater メソッドが設定されている場合ソートされるが、 sort イベントを発火しない。

options.silenttrue で add イベントを発火しない。
options.sortfalse でソートしない。

collection.pop([options])

  • remove

collection.models の最後尾の model を削除し、remove イベントを発火する。

削除された model も remove イベントを発火する。

model 自体は消去されない。

options.silenttrue で remove イベントを発火しない。

collection.unshift(model, [options])

  • add

collection.models の先頭に model を追加する。Object リテラルを渡すと collection.model に設定されたクラスのコンストラクタに渡され、追加される。追加された model を返し、collection、model ともに add イベントを発火する。

collection.comparator を設定していてもソートしない。

options.silenttrue で add イベントを発火しない。

collection.shift([options])

  • remove

collection.models の先頭の model を削除し、削除した model を返し、remove イベントを発火する。model も remove イベントを発火する。model 自体は消去されない。

options.silenttrue で remove イベントを発火しない。

collection.slice([begin], [end])

collection.models の指定範囲の model を返す。

collection.length

collection.models.length を返す。

collection.comparator

二つの model が引数として渡される。

-1 を返すと手前に、1 を返すと後に、0 を返すとそのままとしてソート処理する。

collection.sort

  • sort

collection.models をソートする。comparator 未定義の場合は例外を投げる。

並びに変化がなくとも sort イベントを発火する。

options.silenttrue で sort イベントを発火しない。

collection.pluck(attribute)

格納している各 model から model.attriubtes.attribute を取得し array として返す。

collection.where(attributes)

collection.models から attributes が一致する model を返す。

collection.url

collection.url()

collection.fetch メソッドで通信先となる URL を設定する。

格納している model に model.urlRoot が設定されていない場合、代替として使われる。

collection.parse(response, xhr)

collection.fetch メソッドで取得した値が model に設定される前に通される。

collection.clone()

同じ collection.models を持つ collection を複製して返す。

collection.fetch([options])

  • request
  • sync
  • error
  • add

collection.url と GET メソッドで通信し、リソースを取得する。collection.url 未設定の場合は例外を投げる。

collection.reset 後、通信開始時に request イベントを発火、正常 HTTP ステータスで sync イベントを発火し、collection.parse が設定されている場合は通して model に渡す。model.validate に失敗した場合、例外を投げる。異常 HTTP ステータスで error イベントを発火する。

options.silenttrue で add イベント、reset イベントを発火しない。
options.addtrue で reset を行わない。
options.mergetrue で同一 id の model が存在した場合、model.attriubtes を反映する。

collection.create(model, [options])

  • add

collection.url に POST メソッドで通信し、リソースの作成を要求する。

options.silenttrue で add イベントを発火しない。
options.waittrue で model の追加をサーバーの応答があるまで待つ。

Router

Backbone.Router.extend([properties], [classProperties])

Router を継承したクラスを作成する。

properties インスタンスプロパティ

classProperties 静的プロパティ

new Router([options])

コンストラクタ。

router.initialize([options])

コンストラクト時に呼ばれる。options はコンストラクタに渡されたもの。

router.routes

  • route:callbackName

URL hash に対する callback を設定する。

URL がマッチすると route:callbackName イベントを発火する。

hash : callbackcallback
hash/:arg1/:arg2 : callbackcallback(arg1, arg2)
hash/:arg1(/:arg2) : callbackcallback(arg1, [arg2])
hash/*args : callbackcallback([*args])

router.route(route, name, [callback])

個別に route に対する callback を設定する。

route には正規表現を使用できる。

router.navigate(fragment, [options])

  • route

fragment の URL に遷移する。

options.triggertrue で router.route に設定した callback が呼ばれ、route イベントを発火する。
options.repkacetrue で history を追加せずに上書きする。

History

Backbone.history.start([options])

Router がつくられたときに hashChange イベントや route イベントを監視するために呼ばれる。

options.pushStatetrue でpushState を明示的に使用する。
options.hashChangefalse で hash 遷移を抑制する。
options.roothistory の root を設定。

sync

Backbone.sync(method, model, [options])

対象となる model の attributes を非同期に送受信する。

options jQuery.ajax の引数に渡す値。

Backbone.ajax(settings)

jQuery.ajax へのショートカット。オーバーライドしてアクセス方法を変えることができる。

Backbone.emulateHTTP

true で PUT、DELETE のかわりに POST を使う。

本来の値は X-HTTP-Method-Override に入る。

Backbone.emulateJSON

true で MINE タイプが application/x-www-form-urlencoded になり、JSON は model に入る。

View

Backbone.View.extend([properties], [classProperties])

Backbone.View を継承した新しいクラスを作成する。

propertiesインスタンスプロパティ
classProperties静的プロパティ

new View([options])

new View([options()])

コンストラクタ。

options は view.options として格納される。

options.model options.collection options.el options.id options.className options.tagName options.attributes はそれぞれ view のプロパティに設定される。

view.initialize([options])

コンストラクト時に呼ばれる。options はコンストラクタに渡されたもの。

view.options

コンストラクタに渡された options。

view.el

view.el()

view に関連付く DOM 要素。view.events はこれに対して設定される。

view.$el

view.el を jQuery オブジェクトに変換したもの。

view.setElement(element, [delegate])

view.el を再設定する。view.events は旧 view.el から削除され、element に関連づけられる。

dlegate = false でイベントを引き継がない。

view.model

view.collection

view が使用する model や collection

view.tagName

view.tagName()

view.id

view.id()

view.attributes

view.attributes()

view.className

view.className()

view が作成する DOM 要素の tag、id、attribute、class を設定する。コンストラクタで el を設定していると無視される。

view.$(selector)

view.$el.find(selector)

view.render()

view.el に設定されている DOM 要素に対する操作するメソッド。

view.remove()

view.el および view.events を除去する。

view.make(tagName, [attribute], [content])

DOM 要素を作成する。

view.events

view.events()

view.el をルートとした DOM ツリー内の要素で発火したイベントに対し callback を設定する。

DOM ツリーに新しい要素が追加された場合、自動的に関連づけが行われる。

view.delegateEvents([events])

既存の view.events を除去し、events を設定する。

view.undelegaateEvents()

delegateEvents で設定したイベントを除去する。

view.cid

自動的に振られるユニークな識別子。