如何在视图中获取路径url参数?

时间:2012-08-10 10:03:39

标签: url backbone.js coffeescript chaplinjs

我在CoffeeScript上使用Backbone.js和Chaplin.js。我有一个挑战。如何在路由视图中获取url params?

routes.coffee:

define ->     
  'use strict'
  (match) ->  
    match "account/albums/:page", "accounts#albums"


define [                                                      
  'chaplin'                                                   
  'collections/albums'                                        
  'views/form_view'                                           
  'views/inline/album'                                        
  'text!template/account/_form_image.html'                    
  'text!template/account/list_albums.html'                    
], (chaplin,                                                  
  Albums,                                                   
  FormView,                                                 
  AlbumView,                                                
  formTemplate,                                             
  template                                                  
) ->                                                          
  'use strict'                                                

  class AccountAlbums extends chaplin.CollectionView          
    collection: new Albums                                    
    itemView: AlbumView                                       
    template: template                                        
    containerMethod: 'html'                                   
    listSelector: '[data-placeholder=albums-tile]'            

    # TODO: understand how to get router arguments in the view
    initialize: (options) ->                                  
      super                                                   
      @on 'addedToDOM', => @collection.fetch()                
      # Need to something like this.                          
      # But I do not know how to get it.                      
      #@collection.fetch                                      
      #  data:                                                
      #    page: page                                         

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但为了完整起见,这是一个答案:

您的路由是将数据发送到控制器(albums)内的accounts方法,该方法未在上面的代码中显示。 该方法应如下所示:

  albums: (params, route, options) ->
    @collection = new Albums()
    @view = new AccountAlbums collection: @collection
    @collection.fetch
      data:
        page: params.page

视图不应该打扰检索数据,控制器的工作就是告诉集合获取数据。然后视图自动呈现它。