backbone-railsを触ってみた


backbone-railsを触ってみたのでメモです。

https://github.com/codebrew/backbone-rails

インストール

bakcbone-railsrailsの3.1系で使えます。
railsのプロジェクトを作り、Gemfileに以下を記述します。

gem rails-backbone

あとはbundle install

bundle install

準備

使い始める前に準備が必要です。

rails g backbone:install

blogという名前でプロジェクトを作った場合、以下のようにファイルが生成されます。

├── javascripts
│   ├── application.js
│   └── backbone
│       ├── blog.js.coffee
│       ├── models
│       ├── routers
│       ├── templates
│       └── views

models、routersなどの各フォルダは空です。
生成されたblog.js.coffeeを見れば、どのようなネームスペースを意図しているのかわかります。

window.Blog =
  Models: {}
  Collections: {}
  Routers: {}
  Views: {}

scaffold

rails側とbackbone側のscaffoldを実行することで、とりあえずbackbone.jsを使ったCRUD操作がすぐできるようになります

rails g scaffold Post title:string content:string
rails g backbone:scaffold Post title:string content:string

backbone:scaffoldではmodel、routers、templates、viewsの下に必要なファイルが生成されます。
以下はRouterの例です。

class Blog.Routers.PostsRouter extends Backbone.Router
  initialize: (options) ->
    @posts = new Blog.Collections.PostsCollection()
    @posts.reset options.posts

  routes:
    "/new"      : "newPost"
    "/index"    : "index"
    "/:id/edit" : "edit"
    "/:id"      : "show"
    ".*"        : "index"

  newPost: ->
    @view = new Blog.Views.Posts.NewView(collection: @posts)
    $("#posts").html(@view.render().el)

  index: ->
    @view = new Blog.Views.Posts.IndexView(posts: @posts)
    $("#posts").html(@view.render().el)

  show: (id) ->
    post = @posts.get(id)

    @view = new Blog.Views.Posts.ShowView(model: post)
    $("#posts").html(@view.render().el)

  edit: (id) ->
    post = @posts.get(id)

    @view = new Blog.Views.Posts.EditView(model: post)
    $("#posts").html(@view.render().el)

きれいに整理されているので勉強になります。

あとはdb:migrateして、posts/index.htmlを修正し、backbone.jsの初期処理を行わせます

<div id="posts"></div>

<script type="text/javascript">
  $(function() {
    // Blog is the app name
    window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>});
    Backbone.history.start();
  });
</script>

先日触ってみたbrunchもそうですが、ある程度枠組みを決めてくれるのでとっつきやすいと思います。
とくにscaffoldで動くコードが生成されるのがよいです。