cle*_*lem 3 ruby-on-rails backbone.js
以前,我的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)
Run Code Online (Sandbox Code Playgroud)
导航到时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)
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.但是,显然有一点延迟,因为每次切换路由时都会重新获取集合.这是一个很好的Backbone练习吗?不确定是否有更好的方法来做到这一点.
这是jQuery的Deferred()方法的一个很好的用例.
只需创建一个Deferred对象并将其附加到路由器.然后在initialize方法中获取集合并调用resolve()
Deferred对象.您的索引和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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1348 次 |
最近记录: |