页面重新加载后,Backbone单一视图不起作用

时间:2013-10-27 17:04:20

标签: javascript jquery backbone.js coffeescript

如果我单击我的骨干应用程序的列表视图中的链接,则会按原样呈现单个视图。在浏览器历史中来回导航也可以。但是,如果我在浏览器中重新加载页面(单个视图)或手动输入该特定单个视图的URL,则它不起作用。该集合不包含任何模型。在这种情况下,如何获得渲染单个视图所需的特定模型?谢谢

main.coffee

  class window.MovieSingleView extends Backbone.View
    tagName: 'div'
    className: 'row'

    initialize: ->
      @template = _.template ($ '#movie-single-view-template').html()

    render: ->
      that = @

      @model.deferred.done ->
        ($ that.el).html(that.template that.model.toJSON())

      @

  class window.Router extends Backbone.Router
    routes:
      '': 'index'
      'movies/:id': 'movieSingleView'

    initialize: ->
      @collection = new Movies()
      @collection.fetch
        reset: true

    index: ->
      moviesView = new MoviesView
        # collection: window.movies
        collection: @collection

      ($ '#container')
        .empty()
        .append moviesView.render().el

    movieSingleView: (id) ->
      # movie = window.movies.get id
      # decoratedMovie = new DecoratedMovie movie

      movie = @collection.get id
      decoratedMovie = new DecoratedMovie movie

      movieSingleView = new MovieSingleView
        model: decoratedMovie

      ($ '#container')
        .empty()
        .append movieSingleView.render().el

  $ ->
    window.app = new Router()

    Backbone.history.start
      pushstate: true

    # window.movies.fetch
    #   reset: true

的index.html

<script type="text/template" id="movie-view-template">
  <td><%= _year %></td>
  <td><a href="#/movies/<%= _id %>"><%= _title %></a></td>
  <td><%= _watched %><td>
  <td><span class="glyphicon glyphicon-remove pull-right remove"></span></td>
</script>

1 个答案:

答案 0 :(得分:1)

在您的收藏完成提取之前,您的单个视图正在呈现。因此,您只需在集合完成后呈现视图!