0

こんにちは、私は次のようなバックボーンアプリを持っています:

code.js.コーヒー

window.Code =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  initialize: ->
   new Code.Routers.Todos();
   Backbone.history.start()

$(document).ready ->
  Code.initialize()

todos_router.js.coffee

class Code.Routers.Todos extends Backbone.Router
    routes:
        '': 'index'
        'todos/:id': 'show'

    initialize: ->
        @collection = new Code.Collections.Todos()
        @collection.fetch()
    index: ->
        view = new Code.Views.TodosIndex(collection: @collection)
        view.render()
        $('#container').html(view.el)

    show: (id)->
        alert "#{id}"

todos.js.coffee --> コレクション

class Code.Collections.Todos extends Backbone.Collection
  url: '/todos'

todos_index.js.coffee

class Code.Views.TodosIndex extends Backbone.View

  template: JST['todos/index']

  initialize: -> 


      this.collection.on('reset',this.render,this)

  render: ->
      $(@el).html(@template(todo: this.collection))

問題は、テンプレートでコレクションをレンダリングして長さを取得すると、データベースに 1 つのレコードがあるにもかかわらず結果が 0 になることです。ここで何が間違っていますか?this.collection のコンソール出力は次のとおりです。

Todos {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/todos"…}
_byId: Object
_events: Object
length: 1
models: Array[1]
__proto__: ctor

ありがとう!

4

1 に答える 1

0

resetコレクションのフェッチでイベントを発生させるのに問題がありました。リセットされるコレクションに特に関心がありますか、それともフェッチが API からデータを取得する操作を完了したときにのみ関心がありますか? 後者の場合は、ビューで次のコードを試してください。

todos_index.js.coffee

class Code.Views.TodosIndex extends Backbone.View
  template: JST['todos/index']

  initialize: -> 
    @collection.on 'sync', @render

  render: =>
      $(@el).html(@template(todo: @collection))

各イベントが発生するタイミングの詳細については、公開されたイベントのリストを参照してください。fetchまた、このメソッドは、特定のイベントが発生するかどうかを指定するさまざまなブール フラグを使用することにも注意してください。

本当にイベントにフックする必要があるreset場合 (つまり、コレクションの内容がいつになったかを知りたい場合) は、次のようなことを試すことができます。

todos_router.js.coffee

class Code.Routers.Todos extends Backbone.Router
    routes:
        '': 'index'
        'todos/:id': 'show'

    initialize: ->
        @collection = new Code.Collections.Todos()
        @collection.fetch
          reset: true
          silent: false

    index: ->
        view = new Code.Views.TodosIndex(collection: @collection)
        view.render()
        $('#container').html(view.el)

    show: (id)->
        alert "#{id}"

todos_index.js.coffee

class Code.Views.TodosIndex extends Backbone.View
  template: JST['todos/index']

  initialize: -> 
    @collection.on 'reset', @render

  render: =>
      $(@el).html(@template(todo: @collection))

二次的な提案として、ビュー間でコレクションを再利用する必要がない限り、 @collection をルーターに保持するのではなく、ビューにプッシュすることをお勧めします。

于 2013-04-28T15:14:43.843 に答える