0

Backbone relational is too messy for me and I can't seem to debug it. I am trying to avoid using this asset.

I have two collections in my Backbone app.

Voice.Collections.Posts and Voice.Collections.Comments

This is my router:

class Voice.Routers.Posts extends Backbone.Router
        routes:
                '': 'index'
        initialize: ->
                @collection = new Voice.Collections.Posts()
                @collection.reset($('#container').data('posts').reverse())
        index: ->
                view = new Voice.Views.PostsIndex(collection: @collection)
                $('#container').html(view.render().el)

I want my router to have a method that filters my comment collection according to a url with the post id ( as my comments - post relational key, post_id) so basically "posts/12"(posts/:id) will call a function showComments: (id) -> which will take the id and initialize a collection of comments which only contain comments where 'post_id' is equal to 12 ("id").

Could I sort the collection from my router? something like this? (this doesnt work)

class Voice.Routers.Posts extends Backbone.Router
        routes:
                '': 'index'
                'post/:id/': 'showComments'
        initialize: ->
                @collection = new Voice.Collections.Posts()
                @collection.reset($('#container').data('posts').reverse())
        index: ->
                view = new Voice.Views.PostsIndex(collection: @collection)
                $('#container').html(view.render().el)
        showComments: (id) ->
                @comCollection = new Voice.Views.Collections.Comments()
                @comCollection = @comCollection.where ->
                      @model.get('post_id') = id
                comview = new Voice.Views.CommentsIndex(collection: @comCollection)
                $('#comContainer').html(comview.render().el)

but this doesn't work because the @comCollection needs to be intialized. I'm just not sure how I should do this. I would also settle for the comment collection being rendered as view from another views event trigger.Help is appreciated.

EDIT:

Would I have to use Backbone.navigate? Backbone.navigate creates a bad smell.

godzilla3000
  • 246
  • 3
  • 23

1 Answers1

1

My CoffeeScript is a bit rusty, so I can't remember exactly what:

@comCollection = @comCollection.where ->
                  @model.get('post_id') = id

translates as in normal Javascript. However, it absolutely should work if used right, so perhaps if you tried a simpler syntax:

this.comCollection = this.comCollection.where({post_id: id});

you might have better success? If not, you may want to drop in to the debugger and check what @comCollection actually has in it after you make that call.

machineghost
  • 33,529
  • 30
  • 159
  • 234