2011-12-20 20 views
1

バックボーンでちょうど始まる&コレクションからモデルを取り出す方法とちょっと混乱します。バックボーン/ Javascriptの検査:コレクションからモデルを取得できません

index: (date) -> 
    @days = new Demomanager.Collections.DaysCollection(@options) 
    @days.reset @options.days 
    @days.fetch() 
    @view = new Demomanager.Views.Days.IndexView(days: @days) 
    $("#calendar").html(@view.render().el) 

次のビューに渡す:私はChromeで(options.days @)ビューでその最後の行を検査する場合

class Demomanager.Views.Days.IndexView extends Backbone.View 
    template: JST["backbone/templates/days/index"] 

    initialize: (options) -> 
    _.bindAll(this, 'addOne', 'addAll', 'render') 
    @options.days.bind('reset', @addAll) 
    console.log @options.days 

説明を与えるために、私は次のルータの方法を持っていますインスペクタでは、DaysCollectionが返されます.DescentCollectionには、36個のエントリがある 'models'配列が含まれています(これは期待どおりです)。私は

console.log @options.days.models 

console.log @options.days 

を変更したときに

はしかし、私は空の配列、代わりの36モデルとの配列を取得します。

最後に、コンソール自体(window.router.days.models)から同じオブジェクトにアクセスすると、36個のモデルが期待通りに表示されます。

要するに、何が起こっているのですか。ビュー内からこれらのモデルにアクセスするにはどうすればよいですか?

多くのおかげで...

答えて

1

あなたはあなたのビューにフェッチ移動したい:

var IndexView = Backbone.View.extend({ 
    collection: new Demomanager.Collections.DaysCollection(options), 
    template: myTemplate, 

    initialize: function() { 
     $("#calendar").html(_.template(myTemplate, {})); 

     this.collection.fetch(); 
     this.collection.reset(null, options.days); // don't know how coffeescript works, but first arg here is models set not the options object 

     this.collection.bind("add", this.addOne, this); 
    }, 


    addAll: function() { 
     this.collection.each(this.addOne, this); 
    }, 
    addOne: function(model) { 
     $(this.el).append(new ChildView({model: model})); 
    } 

}); 
2

たぶんその原因は、あなたが非同期呼び出しを行います。したがって、ビューのコンストラクタにoptions.daysを記録すると、データはまだロードされませんでした。成功コールバックdays.fetchでビューを作成する方が良いでしょう。このようにすると、ロードが失敗したときに別のビューを開始することもできます。

関連する問題