我现在道歉,自从我上次在Rails工作以来已经有一段时间了,这是我第一次尝试使用backbonejs。我在项目中使用Rails和backbonejs(最新的 - rails 4.1.1,主干1.1.2)。 rails方面设置正确并返回JSON作为主干喜欢它,如下所示:
http://localhost:3000/artists
[
{
"id":1,
"name":"Jeff Beck",
"sort_name":"Beck, Jeff",
"musicbrainz_id":"14a4bc78-1c2d-4ca7-8d1b-9b58076a2a17"
}
]
来自rails控制器的内容如下:
class ArtistsController < ApplicationController
def index
render :json => Artist.all
end
[...]
end
骨干模型看起来像这样。它在coffeescript中。
class AppName.Collections.HomeCollection extends Backbone.Collection
model: AppName.Models.Home
url: -> '/artists'
parse: (response) ->
console.log "parse response %o", response
response
class AppName.Models.Home extends Backbone.Model
paramRoot: 'home'
defaults: {
name: 'default name',
sort_name: 'default sort_name'
musicbrainz_id: "default musicbrainz_id"
}
骨干路由器:
class AppName.Routers.HomeRouter extends Backbone.Router
initialize: (options) ->
@homecollection = new AppName.Collections.ArtistsCollection
@homecollection.reset
routes:
"" : "index"
".*" : "index"
index: ->
@homecollection.fetch
success: (collection, response, options) ->
console.log "success fetch collection %o, response %o, options %o",
collection, response, options
new AppName.Views.Home.IndexView collection: collection
error: ->
console.log "HomeRouter error fetch, response %o"
undefined
更新:fetch()
success
回调中的console.log输出如下所示:
"success fetch
collection"
ArtistsCollection
_byId: Object
_events: Object
_listenId: "l3"
length: 1
models: Array[1]
__proto__: ctor
",
response "
ArtistsCollection
_byId: Object
_events: Object
_listenId: "l3"
length: 1
models: Array[1]
__proto__: ctor
",
options "
Object
error: function (resp) {
parse: true
}
success: function (resp) {
__proto__: Object
}
然后最后是观点:
AppName.Views.Home ||= {}
class AppName.Views.Home.IndexView extends Backbone.View
el: '#home'
tagName: 'ul'
template: JST["backbone/templates/home/index"]
initialize: ->
@listenTo @collection, 'sync', @render
console.log "home index_view init, Home.IndexView.collection %o", @collection
render: ->
$(@el).html @template collection: @collection
return this
我挣扎的地方是我在骨干路由器中的获取请求返回一个集合对象,但从我读过的内容我应该得到JSON?来自获取请求的console.log显示传递给success
的收集和响应参数的相同对象
如果我尝试在浏览器控制台中与骨干交互,我可以执行以下操作:
var home = new AppName.Collections.ArtistsCollection
var home = home.fetch()
JSON.stringify(home.responseJSON)
"[{"id":1,"name":"Jeff Beck","sort_name":"Beck, Jeff","musi... etc"}]"
所以,毕竟,我哪里出错了,为什么我不能从rails请求中获取JSON数据并将其传递给我的骨干视图模板?