У меня простая, но запутанная проблема. У меня есть следующий фрагмент кода:Модель мачты отсутствует, но я не понимаю, почему
<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
CoffeeScript:
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
с идентификатором restuarant_locations
. Тот факт, что id
установлен в restaurant_locations
, делает определенное чувство; URL-адрес, который я делаю, - 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)
'showVideo.model' происходит от' нового ShowView ({model: myModelInstance}) '. Извините, но я должен сказать, что если вы не знаете, что вам следует начать расследование с помощью Backbone в гораздо более простых сценариях. – fguillen
Вы копировали pasta? – jakee
Возможно, я должен был упомянуть: я на Rails и использую жемчужину «backbone-rails», которая автоматически генерирует много кода. Я бы ожидал, что он будет работать без меня, чтобы отлаживать его сгенерированный код, но это не так. –