Search code examples
coffeescriptspine.js

Spine.js AJAX fetching record from server


I have simple app which displays list of recrods, also user whould be able to edit barticular record by id. Because list is big, i don't fetch it as whole, but partially via Product.fetch(data: $.param(page: 1)).

Then when someone try to edit record, i call Product.find(id) and if recrord was already prefetched with fetch then it works fine, but when record not yet fetched then i got error like: "Product" model could not find a record for the ID "1152"

So, the question is why find not performing ajax call and how to make it perform it or maybe there is another solution exists ?


Solution

  • Spine.find only looks in the already loaded records. Doing an ajax request isn't the function of find. So you have to try-catch your find and when it gives this error, you have to fetch it.

    id = 1152
    
    try
      product = Product.find id
    catch err
      Product.fetch(
        data:
         id: id
        processData: true
      )
      # Try again after Product.refresh
    

    To be honest, I think this isn't a nice way to do it, but it is how spine works... I rather have it fetch it automatically, or at least not throwing an error on find.