Search code examples
ajaxcoffeescriptspine.js

spine.js: "Uncaught Unknown record"


I use spine.js in conjunction with the Spine.Ajax Module to load stuff via JSON from the Server. I've probably run into some syncronisation problem. I have a sidebar which just binds to the refresh and change events and then is rendered:

Survey.bind 'refresh change', @render

I also have set up some routes, which display a survey when the user accesses it via #/survey/:id. This is my controller:

class App.Surveys extends Spine.Controller
  className: 'surveys'

  constructor: ->
    super

    @append(@sidebar = new App.Sidebar)       # Sidebar to select surveys
    @append(@surveys = new App.SurveysStack)  # Show survey details survey

    @routes
     '/surveys/:id': (params) ->
       @sidebar.active(params)
       @surveys.show.active(params)

    Survey.fetch()

As you see, Survey.fetch() is called after the initialization, which does not pose a problem to the sidebar. However, it seems, that it poses a problems to the surveys Show controller (which is called by a Spine.Stack called App.SurveyStack):

class Show extends Spine.Controller
  constructor: ->
    super
    @active @change

  change: (params) =>
    # There is a bug! If Survey is not fetched when we run this,
    # this throws an error.
    @item = Survey.find(params.id)
    @render()

  render: ->
    @html @view("surveys/show")(@item)

I keep getting errors from the commented part of the source: Uncaught Unknown record. Can I make the Survey.find() function block until Survey.fetch() is done?


Solution

  • You are correct in your diagnosis that you can't find an item before you've fetched it from the server.

    The easiest solution is to bind an event to the Survey.fetch() call like so:

    Survey.bind 'refresh change', @method_to_call
    

    Let me know if that helps!