user1028432
user1028432

Reputation: 137

Backbone fetch collection + Rails

js files:

class BackApp.Collections.Posts extends Backbone.Collection
  url: '/api/posts'
  model: BackApp.Models.Post

class BackApp.Models.Post extends Backbone.Model

class BackApp.Routers.Posts extends Backbone.Router
  routes:
    '': 'index'
  initialize: ->
    @collection = new BackApp.Collections.Posts
    @collection.fetch()
  index: ->
    #view = new BackApp.Views.PostsIndex(collection: @collection)
    #$("#container").html(view.render().el)

rails routes:

  scope "api" do
    resources :posts
  end
  root :to => 'main#index'

So , when i am trying fetch collection in chrome console like :

collection = new BackApp.Collections.Posts
collection.fetch()
collection.length # => 3

But if i wrote it (console.log) in posts routes file in initialize function it show 0 Why?

Upvotes: 1

Views: 483

Answers (1)

SergeyKutsko
SergeyKutsko

Reputation: 697

@collection.fetch() executes async.

When you try chrome console data already loaded when you use console.log(), but when you try it with js code data is to loaded yet when you use console.log()

You should use success callback to know length of collection when it loaded:

@collection.fetch(
  success: (collection, response, options) ->
    console.log collection.models.length
)

Upvotes: 1

Related Questions