lxyuma BLOG

開発関係のメモ

Marionette.js(Backbone.js)のチュートリアル with yeoman その1(準備からサーバー側実装まで)

Marionette.jsのチュートリアルを書く。

特に、yeoman製のgenerator-marionetteを使って、

railsみたいに、楽しながら、進めていく。

  • 量が多くなったので、何度かに分けて書く。

    • この記事は、yeomanによる準備から、node+expressによるサーバー側まで。(baucis という楽チンな仕組みを使う)

Marionette.jsとは?

この前作ったslideをご参考に。

インストール

以下のgenerator-marionetteのgithubのページを参照

特にハマる事は無い。多分ね。

project作成

project名を「todo-mario」とする。

mkdir todo-mario

cd todo-mario

yeomanでprojectのひな形を作る

$ yo

・・・略・・・(おじさんの顔が出て来る)

[?] What would you like to do? (Use arrow keys)

と聞かれるので、

Run the Marionette generator (0.1.3) 

を選択。Enter.

色々聞かれるが、全部、defaultでOK!

Out of the box I include HTML5 Boilerplate, jQuery, Backbone.js, Marionette, Handlebars, Require and Modernizr.
[?] Would you like to install the full express app or simply the marionette generators? Yesn) Y
[?] Would you like to include MongoDB for storage? Yes
[?] Would you like to include Socket IO for real time communication? Yes
[?] Would you like to include Baucis for REST? Yes
[?] Where do you want the Bower components installed? bower_components

Baucisは、Rest+CRUD処理まとめて簡易に作れる仕組み。

注意1)ここで、以下のエラーメッセージが出た場合。

npm ERR! Error: EMFILE, too many open files

ファイルディスクリプターの規定値を超えてるので、

以下の通り、調整して、初めからやり直す。

$ ulimit -n
256
$ ulimit -n 1024

注意2:lodashのtar.js

以下のように、lodashのtar.jsが無いとか言われた人。

> node ./bin/post-install.js

  SOLINK_MODULE(target) Release/bson.node: Finished

module.js:340
    throw err;
          ^
Error: Cannot find module '../node_modules/lodash/vendor/tar/tar.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)

以下のURLを参考にして、 grunt-requirejsを"grunt-contrib-requirejs"に変更して入れ直す。

ディレクトリ構成について

yeomanによるひな形作りが終わると、以下の状態になってるはず。

$ ls
Gruntfile.js  bower.json    package.json    test
app     node_modules    server

主要なファイル/ディレクトリ

  • app:client側のjs
    • app/scripts:js入れる所
    • app/templates:jsのテンプレート入れる所
    • app/styles:css
  • server:サーバー側のjs
  • test:テスト用のjs

実行方法

ここで、一旦、gruntを起動して、作られた物を見てみる

$ grunt

ブラウザが勝手に起動して、localhost:9000のurlに対して、

「CONGRATS!」と表示されたら、正常。

もし、この時に、コンソールに以下のエラーメッセージが出たら、

connection error: [Error: failed to connect to [localhost:27017]]

27017のポートはmongodbなので、mongodbを起動していないという事。

以下のコマンドでmongodbを起動しよう。

sudo mongod --fork --logpath /var/log/mongodb --logappend

今回作るもの

よくある、todoMVCみたいなのを作る。

http://todomvc.com/architecture-examples/backbone/

ここまでちゃんとしたものじゃないけど、

  • todoの新規作成と、

  • todoの済みclickと、

  • allか済みだけかのフィルタリングが出来る程度のもの。

サーバー側

server/app.jsに少し手を入れる。

これが、express(node)のサーバー側ソース部分。

diff --git a/server/app.js b/server/app.js
index 01ba505..3d2278b 100644
--- a/server/app.js
+++ b/server/app.js
@@ -11,22 +11,22 @@ var mongoose = require('mongoose');
 
 
 // start mongoose
-mongoose.connect('mongodb://localhost/sit');
+mongoose.connect('mongodb://localhost/test');
 var db = mongoose.connection;
 
 db.on('error', console.error.bind(console, 'connection error:'));
 db.once('open', function callback () {
 
-       /* test schema */
-    var testSchema = new mongoose.Schema({
-        test: String
+    var taskSchema = new mongoose.Schema({
+        title: String,
+        finished: Boolean
     });
 
-    var Test = mongoose.model( 'test', testSchema );
+    var Task = mongoose.model('task', taskSchema );
 
     /* set Baucis */
     baucis.rest({
-        singular: 'test'
+        singular: 'task'
     });
 
        var app = express();

mongoose 書いた事ない人は、よければ、前に書いた資料を。 ※整理してないから、少しごちゃごちゃしてるかも。

Baucisを使って、mongodbのCRUDを任せる。

Baucisとは?

url

Restに対して、決まったCRUD 処理を行うもの。

(Rest = getで来たら、取得、postで来たら更新のように、http methods + urlの組み合わせでリソースを変える考え方の事。)

Postで来たら、createして、とか書かなくて済む。

1行書くだけで、rails で言うscaffold の各種メソッドをやってくれる。

早速確認してみる。

app.use('/api/v1', baucis());

この箇所が、endpointを指定している所。

早速、以下のURLを指定して、確認してみる。

  • http://localhost:9000/api/v1/tasks
    • ※この最後のパスが複数形になっている点に注意。
    • うまくいかない時は、複数形の形が正しいか考えよう。ちなみにbaucisに、「todo」で登録した場合、url の最後のパスはtodosではなく、todoesとかになってる。baucis側で複数形指定できたと思うので、この辺りは必要に応じて確認を。
    • このurl のパターンはgithub page を参照。

これで、ブラウザはこんな表示をしているはず。

[]

今は、mongodb上に何もデータが無いので、表示されない。

ここに、データを入れてみる。

RestClientツール

なんでもいいのだが、今回は、chromeアプリのAdvanced Rest Clientを使う。

RestClient系のツールはググればいっぱいあるので、好きなのを使えば良い。

このurlに対して、{"title":"TEST"}をPOSTする。

この時、Content-Typeをjsonにしておかないとおかしくなるので、注意。

Postした後に、以下のアドレスにアクセスしてみると、

postしたデータを表示しているはず。

その1はおしまい。

これで、サーバー側のAPI が出来た!(簡単ですね)

ここまでは、どちらかというと、Node/express やyeoman の話。

次に、メインとなる、marionette のクライアント側のプログラミングについて書く。

その2

http://lxyuma.hatenablog.com/entry/2013/10/11/000356