[英]Backbone + Rails collection fetching
以前,我的主干路由器看起來像這樣:
class App.Routers.ThingsRouter extends Backbone.Router
routes: '': 'index'
routes: 'previews/:id': 'show'
initialize: ->
@collection = new App.Collections.ThingsCollection
@collection.fetch
index: ->
view = new App.Views.ThingsIndex(collection: @collection)
$('#app-container').html(view.render().el)
show: (id) ->
@model = @collection.get(id)
view = new App.Views.ThingsShow(model: @model)
$('#app-container').html(view.render().el)
當導航到http://localhost
時,我會呈現index
視圖,當單擊單個元素時,我會呈現show
視圖。 但是,如果我直接訪問http://localhost/things/1
(即通過鍵入 URL),則不會呈現show
視圖。 我意識到這是因為視圖是在@collection.fetch
完成之前呈現的。 我將路由器更改為以下內容:
class App.Routers.ThingsRouter extends Backbone.Router
routes: '': 'index'
routes: 'previews/:id': 'show'
initialize: ->
@collection = new App.Collections.ThingsCollection
index: ->
@collection.fetch success: =>
view = new App.Views.ThingsIndex(collection: @collection)
$('#app-container').html(view.render().el)
show: (id) ->
@collection.fetch success: =>
that.model = that.collection.get(id)
view = new App.Views.ThingsShow(model: @model)
$('#app-container').html(view.render().el)
哪個工作正常。 但是,顯然有一點延遲,因為每次我切換路由時都會重新獲取集合。 這是好的 Backbone 實踐嗎? 不確定是否有更好的方法。
這是 jQuery 的Deferred()方法的一個很好的用例。
只需創建一個 Deferred object 並將其附加到路由器即可。 然后在初始化方法中獲取集合並在 Deferred object 上調用resolve()
。您的 index 和 show 方法可以訂閱done
回調並實例化視圖。 在獲取集合之前,不會運行此完成的回調。 如果它已經被獲取,那么它會立即運行。
class App.Routers.ThingsRouter extends Backbone.Router
routes: '': 'index'
routes: 'previews/:id': 'show'
initialize: ->
@collectionFetched = new $.Deferred
@collection = new App.Collections.ThingsCollection
@collection.fetch success: ->
@collectionFetched.resolve()
index: ->
that = this
@collectionFetched.done ->
view = new App.Views.ThingsIndex(collection: that.collection)
$('#app-container').html(view.render().el)
show: (id) ->
that = this
@collectionFetched.done ->
that.model = that.collection.get(id)
view = new App.Views.ThingsShow(model: that.model)
$('#app-container').html(view.render().el)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.