私は単純だが紛らわしい問題を抱えています。次のコードがあります。
<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
はある程度の意味があります。ヒットしている URL はhttp://localhost:3000/restaurant_locations
. しかし、それが目的の URL である場合index
は、 ではなく関数を呼び出す必要があるようです。show
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)