I am trying to access items of an array in a model and it’s raising errors but seems to be finding the correct attribute and writing it to the console still
class GD.Views.Place extends Backbone.View
template: JST['mobile/templates/place']
initialize: ->
@model.on('change', @render, this)
render: ->
$(@el).html(@template(place:@model, open:@openNow() ))
console.log @model.get("coordinates")
console.log @model.get("coordinates")[0]
console.log @model.get("coordinates")[1]
console.log("done")
this
openNow: ->
...
The view is not rendering on-screen and I am seeing this message in my console
Uncaught TypeError: Cannot read property '0' of undefined
GD.Views.Place.Place.render
GD.Routers.Main.Main.place
_.extend.route
(anonymous function)
_.some._.any
_.extend.loadUrl
_.extend.start
window.GD.init
(anonymous function)
jQuery.Callbacks.fire
jQuery.Callbacks.self.fireWith
jQuery.extend.ready
DOMContentLoaded
[51.4528837, -0.9739059999999428]
51.4528837
-0.9739059999999428
done
The error message is referring to the 2nd and 3rd console.log lines above. It also seems to be raising errors when accessing further attributes in embedded hashes.
I don’t understand why this is happening or how to work around it. Thanks for the help/patience in advance!
The usual pattern with a Backbone view is this:
If you combine that with a common pattern for initializing a model:
then you can get this:
That would allow the
v.render()inside theappendcall to happen before the model has been fetched from the server. In your case, that would mean that@model.get('coordinates')would beundefinedin thev.render()call above and you would get:then, the
m.fetch()gets its data from the server and triggers a"change"event, that event would then callrenderon your view and you would get this:That sequence of messages is exactly what you’re seeing in your console.
I’d guess that you’r doing something like this (as above):
Try checking to see if
@modelis actually loaded insiderenderand throw up some sort of “loading…” message if it isn’t; then let the"change"event trigger the “real” rendering.PS: You can use
@instead ofthisin CoffeeScript:You could also use a fat arrow (
=>) to define yourrendermethod and not worry about supply a context to@model.on:Furthermore, if you’re using a recent version of Backbone, you have a
$elin your view instances so you could: