Bond



abstract

+ bondは循環参照を防いでいる
* プロパティのvalueが変化したら自動でbindしたもののvalueも変化するという挙動をさらっと書けるのが重要なポイント

TableViewのCell描画を例にすると、、、、
bondは、宣言的な手続き(arrayが更新したらtableviewを描画し直してくれるメソッドが中にある)
<=>命令的な手続き(関数の中に関数を呼ぶ命令が書いている)

Bond-Demo-Appも良い

#Bond README.mdまとめ

>
Bond is a Swift binding framework that takes binding concept to a whole new level. It's simple, powerful, type-safe and multi-paradigm - just like Swift.
>
Bond was created with two goals in mind: simple to use and simple to understand. One might argue whether the former implies the latter, but Bond will save you some thinking because both are true in this case. Its foundation are few simple classes - everything else are extensions and syntactic sugars.
>
Note: This document describes Bond v4. If you are using a previous version of the framework, check out the Migration to Bond v4 section. Bond v4 is the only officially supported version for Swift 2.0. 


cf) 
syntax sugar(糖衣構文):初心者でもわかるように作られた、本来の構文の様式美を破壊するような簡素な構文



+ map

``` textfieldに書き込まれたtextがprintされる
textField.bnd_text
  .observe { text in
    print(text)
  }
```

``` textfieldに書き込まれたtextに追加してprintしたい時
textField.bnd_text
  .map { "Hi " + $0 } // $0はtextFieldに書き込まれたvalue
  .bindTo(label.bnd_text)
```

+ filter, TouchUpInside

``` event発生時、条件を付記したい時
button.bnd_controlEvent
  .filter { $0 == UIControlEvents.TouchUpInside }
  .observe { e in
    print("Button tapped.")
  }
```

``` 上記の省略記載法。buttonをtapしたら"Button_tapped"がprintされる
button.bnd_tap
  .observe {
    print("Button tapped.")
  }  
```
+ 複数の引数から一つの返り値も出せる

```
combineLatest(emailField.bnd_text, passField.bnd_text)
  .map { email, pass in
    return email.length > 0 && pass.length > 0
  }
  .bindTo(button.bnd_enabled)
```

<br>
>
Bond's power is not, however, in coupling various UI components, but in the binding of a Model (or a ViewModel) to a View and vice-versa. It's great for MVVM paradigm. Here is how one could bind user's number of followers property of the model to the label.
>
Point here is not in the simplicity of value assignment to text property of a label, but in the creation of a binding which automatically updates label text property whenever number of followers change.

``` viewModelのnumberOfFollowersプロパティをlabelに代入
viewModel.numberOfFollowers
  .map { "\($0)" }
  .bindTo(label.bnd_text)
```
``` 別の書き方。こちらも常に同期している
viewModel.username.bidirectionalBindTo(usernameTextField.bnd_text)
```
=>numberOfFollowersのvalueが変化したらその値が自動的にlabelに反映されるのが重要なポイント
<br>

>
Say you have an array of repositories you would like to display in a collection view. For each repository you have a name and its owner's profile photo. Of course, photo is not immediately available as it has to be downloaded, but once you get it, you want it to appear in collection view's cell. Additionally, when user does 'pull down to refresh' and your array gets new repositories, you want those in collection view too.
instead of implementing a data source object, observing photo downloads with KVO and manually updating the collection view with new items, with Bond you can do all that in just few lines:

```
repositories.bindTo(collectionView) { indexPath, array, collectionView in
  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! RepositoryCell
  let repository = array[indexPath.section][indexPath.item]

  repository.name
    .bindTo(cell.nameLabel.bnd_text)
    .disposeIn(cell.onReuseBag)

  repository.photo
    .bindTo(cell.avatarImageView.bnd_image)
    .disposeIn(cell.onReuseBag)

  return cell
})
```

参考：KVOの意味はKey-Value Observingの略で、プロパティーの値の変化を通知してくれる仕組み。[SwiftでKVOを試してみる](http://llcc.hatenablog.com/entry/2015/08/11/235115)


###The Event Producer
>
At the core of the framework is the class "EventProducer". 
It represents an abstract event generator that provides the mechanisms that enable interested parties, called observers, to observe generated events. For example, it can be used to represent a subject with a mutable state, like a variable or an array, and then inform observers of the state change whenever it happens. On the other hand it can represent an action, something without a state, and generate an event whenever the action occurs.

###The Observable
>
The most common use of the event producer is through its subclass "Observable" that can mimic a variable or a property and enable observation of its change. The Observable is a generic type generalized over the wrapped value type. As the EventProducer is also a generic type, generalized over its event type, it is only natural to specialize such event producer to the type of the values it can encapsulate. To create the observable just initialize it with a value:

参考：generic typeについては次の記事によくまとめられています
[Swift ジェネリックス(Generics)](http://blog.codable.co.jp/entry/2014/11/27/211831)

`let captain = Observable(“Jim”)`
>
Swift automatically infers the type of the observable from the passed value. In our example the type of the variable captain is Observable<String>. To change its value afterwards, you can use the method next:

nextメソッドにより、valueをセットでき、valueメソッドでvalueを取得できる。
`captain.next(“Spock”)`

`print(captain.value) // prints: Spock`

>
Now comes the interesting part. In order to make the observable useful it should be observed. Observing the observable means observing the events it generates, that is, in our case, the values that are being set. To observe the observable we register a closure of the type "EventType -> ()" to it with the method observe, where _EventType_ is the event (value) type:

```
captain.observe { name in
  print(“Now the captain is \(name).”)
}

// prints: Now the captain is Spock.
```
>
Now, whenever the value is changed, the observer closure will be called and side effects performed:

```
captain.next(“Scotty” ) // prints: Now the captain is Scotty.
```


bindToは二次元配列じゃないと使えない(FaceBook参照)

ここまでは読んだ。


***
propagate: 繁殖する
prepend: 先頭に挿入する、
observable: 観察すべき、注目すべき
snippet: 断片
asynchronous: 非同時性の
mutable: 変わりやすい

***





##参考
[recruit tech blog](http://tech.recruit-mp.co.jp/mobile/studying-swift-generitics/)

関数型リアクティブプログラミングをするためのオープンソース

キーワード
・Generics
...[The Swift Programming Language; Generics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html)
...[ジェネリクス｜Swift言語を学ぶ](http://tea-leaves.jp/swift/content/%E3%82%B8%E3%82%A7%E3%83%8D%E3%83%AA%E3%82%AF%E3%82%B9)
・type constraint syntax(型制約)
・associated types(関連型)


_____
[お手製Swift Bondでリアクティブプログラミング](http://qiita.com/katryo/items/4f2473b72a629bb4257a "Qiita")

キーワード

- RFP
- 途中なので残りを読んでキーワードを埋める


___
[Solving the binding problem with Swift](http://five.agency/solving-the-binding-problem-with-swift/)

これもまだ読んでないので読んで埋める


c
objectがなくなったらbindも勝手にunbindされるが、cellは再利用されるので勝手にunbindされない
-->prepareforreuseというメソッドがcellにはある
メソッド内部で、onReuseBagにbindの情報を入れておく
->scrollしてcellが再利用される前にprepareforReuseがcallされる
->onReuseBagに入っていたbindはunbindされる
->新たにbindすることが可能

bondではdisposeInすることで再利用する前にunbindをしている？？？？