我有一个简单但令人困惑的问题。我有以下代码:
<div id="restaurant_locations"></div>
<script type="text/javascript">
$(function() {
window.router = new Lunchhub.Routers.RestaurantLocationsRouter({
restaurantLocations: <%= @restaurant_locations.to_json.html_safe -%>
});
Backbone.history.start({pushState: true});
});
</script>
引发此错误:
Uncaught TypeError: Cannot call method 'toJSON' of undefined
但是,如果我取出{pushState: true}
零件,并且不Backbone.history.start()
带任何参数,它就可以正常工作。
在错误旁边,它说show_view.js: 19
。这是该部分的show_view.js
外观:
ShowView.prototype.template = JST["backbone/templates/restaurant_locations/show"];
ShowView.prototype.render = function() {
$(this.el).html(this.template(this.model.toJSON())); // LINE 19
Uncaught TypeError: Cannot call method 'toJSON' of undefined
return this;
}
所以我猜this.model
是未定义的。这是show_view
咖啡脚本:
Lunchhub.Views.RestaurantLocations ||= {}
class Lunchhub.Views.RestaurantLocations.ShowView extends Backbone.View
template: JST["backbone/templates/restaurant_locations/show"]
render: ->
$(@el).html(@template(@model.toJSON() ))
return this
如果我能做到@model
它需要的样子,我想它可能会解决问题。但我不知道@model
从哪里来或什么。
我需要做什么?
编辑:我走得更远了。在下面的show
函数中,id
设置为“restaurant_locations”,当然没有@restaurantLocations
id 为 的成员restuarant_locations
。id
set set to的事实restaurant_locations
有一定的意义;我点击的网址是http://localhost:3000/restaurant_locations
. 但它似乎应该调用index
函数,而不是show
,如果那是我要去的 URL。
class Lunchhub.Routers.RestaurantLocationsRouter extends Backbone.Router
initialize: (options) ->
@restaurantLocations = new Lunchhub.Collections.RestaurantLocationsCollection()
@restaurantLocations.reset options.restaurantLocations
routes:
"new" : "newRestaurantLocation"
"index" : "index"
":id/edit" : "edit"
":id" : "show"
".*" : "index"
newRestaurantLocation: ->
@view = new Lunchhub.Views.RestaurantLocations.NewView(collection: @restaurantLocations)
$("#restaurant_locations").html(@view.render().el)
index: ->
@view = new Lunchhub.Views.RestaurantLocations.IndexView(restaurantLocations: @restaurantLocations)
$("#restaurant_locations").html(@view.render().el)
show: (id) ->
restaurant_location = @restaurantLocations.get(id)
@view = new Lunchhub.Views.RestaurantLocations.ShowView(model: restaurant_location)
$("#restaurant_locations").html(@view.render().el)
edit: (id) ->
restaurant_location = @restaurantLocations.get(id)
@view = new Lunchhub.Views.RestaurantLocations.EditView(model: restaurant_location)
$("#restaurant_locations").html(@view.render().el)