gpt4 book ai didi

ruby-on-rails - Backbone + Rails 集合获取

转载 作者:行者123 更新时间:2023-12-04 23:46:17 25 4
gpt4 key购买 nike

以前,我的 Backbone 路由器是这样的:

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 View ,当单击单个元素时,我会得到 show 呈现的 View 。但是,如果我直接访问 http://localhost/things/1(即通过键入 URL),则不会呈现 show View 。我意识到这是因为 View 是在 @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 对象并将其附加到路由器即可。然后在初始化方法中获取集合并在 Deferred 对象上调用 resolve()。您的 index 和 show 方法可以订阅 done 回调并实例化 View 。在获取集合之前,不会运行此完成的回调。如果它已经被获取,那么它会立即运行。

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)

关于ruby-on-rails - Backbone + Rails 集合获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10000549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com