簡體   English   中英

除了在javascript控制台中,rails on collection上的骨干不起作用

[英]backbone on rails collection fetch does not work except in javascript console

更新:

忘記第一次嘗試,在我的“另一次嘗試”中,它適用於Firefox,但在谷歌瀏覽器中失敗。 原因似乎是firefox彈出警報允許集合有足夠的時間來獲取數據,在我刪除警報后它再次返回0(而不是2)。 似乎on('reset',..)被繞過了


我是骨干新手,正在測試我所擁有的東西

集合文件:

class Blog.Collections.Posts extends Backbone.Collection

  model: Blog.Models.Post

  url: '/bb/posts/list_posts'

模型文件:

class Blog.Models.Post extends Backbone.Model

路由器文件:

class Blog.Routers.Posts extends Backbone.Router
  routes: 'posts/list' : 'list'

  list: ->
    @collection = new Blog.Collections.Posts()
    @collection.fetch success: ->
       alert @collection
       view = new Blog.Views.PostsIndex()
       $('#center').html(view.render(posts: @collection).el)

查看文件:

 class Blog.Views.PostsIndex extends Backbone.View

   template: JST['posts/index']


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

模板文件只顯示帖子的長度。 所以當集合從/ bb / posts / list_posts url中獲取json時,我應該等待它成功完成。 但不知何故,警報返回undefined ,模板呈現長度0

另一種嘗試:

路由器文件:

class Blog.Routers.Posts extends Backbone.Router
  routes: 'posts/list' : 'list'

  list: ->
    @collection = new Blog.Collections.Posts()
    @collection.fetch()
    view = new Blog.Views.PostsIndex(collection: @collection)
    $('#center').html(view.render().el)

查看文件:

 class Blog.Views.PostsIndex extends Backbone.View

   template: JST['posts/index']

   initialize: ->
     @collection.on('reset',@render,this)
     alert @collection.length

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

這次,我得到警告@collection返回Object [Object],但它的長度為0。

fetch在javascript控制台中運行FINE,長度為2.為什么它不起作用?

在這里找到解決方案

Backbone.js - fetch方法不會觸發重置事件

事實證明,“重置”事件的問題從未被解雇過。 正如鏈接中指出的那樣,fetch({reset:true})解決了問題,而不是fetch()。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM