2012-04-15 7 views
1

私はBackbone.jsの新品です。現在のレールアプリに統合しようとしています。レールスクールのチュートリアルに従っていますが、それらを統合することに問題があります。基本的に、私は自分のリソース(プロジェクト)を呼び出してページに表示するようになっています。次のように私のルータに見える:Backbone.jsをRailsで使用すると、@collectionは 'undefined'ですか?

class Placeholder.Routers.Projects extends Backbone.Router 
    routes: 
    '': 'index' 
    'projects/:id':'show' 

    initialize: -> 
    @collection = new CIS196Project.Collections.Projects() 
    @collection.fetch() 

    index: -> 
    view = new Placeholder.Views.ProjectsIndex() 
    $('#container').html(view.render().el) 

    show: (id) -> 
    alert "Project #{id}" 

をし、私の見解は次のようになります。私は、ほとんどのチュートリアルから直接取ったすべてが

class Placeholder.Views.ProjectsIndex extends Backbone.View 

    template: JST['projects/index'] 

    initialize: -> 
    document.write(@collection) 
    @collection.on('reset', @render, this) 

    render: -> 
    $(@el).html(@template(projects: @collection)) 
    this 

。テストのためにdocument.write(@collection)を追加しました。ページのロード時に

、私はエラーを取得する:

projects_index.js:17 Uncaught TypeError: Cannot call method 'on' of undefined

私は正常に私のログに、GETリクエストが正常に通過するため、ルータにfetch()を作り、そしてクロームの中でそれを試しによコンソールでは、フェッチはサイズ1の配列を返すはずですが、代わりにエラーが発生し、コントローラからデフォルトのレールビューがロードされます(なぜこれが発生するのかわかりません。それでもこのエラーが発生すると、document.writeを呼び出さない限り、前のページに戻ります。 document.writeを呼び出すと、@collectionが「未定義」となります。

お手数をおかけしていただきありがとうございます。

答えて

2

あなたのルータでインスタンス変数としてあなたのコレクションを作成している:

class Placeholder.Routers.Projects extends Backbone.Router 
    #... 
    initialize: -> 
    @collection = new CIS196Project.Collections.Projects() 
    #... 

いますが、ビューにそのコレクションを与えることはありません:

index: -> 
    view = new Placeholder.Views.ProjectsIndex() 
    #... 

あなたのビューにコレクションを指定した場合:

collectionインスタンス変数あなたの意見でfine manualから

constructor/initializenew View([options])

[...] There are several special options that, if passed, will be attached directly to the view: model , collection , el , id , className , tagName and attributes .

ビュー、ビューに@collectionを取得するのに十分であるインスタンス化するときだからcollectionオプションを指定

。余談として

console.log(@collection)document.writeは(時々ページ全体を消去するように)不幸な副作用があり、 console.logは、より読みやすい出力を生成します、 document.write(@collection)よりも良いアイデアです。

関連する問題