spine / spine

Lightweight MVC library for building JavaScript applications

Home Page:http://spine.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Model.save() misbehaving when the server returns non-standard JSON

Bowbaq opened this issue · comments

It seems that since 1cdef79 custom JSON from the server is no longer correctly handled.

When I researched this earlier, it seemed that the solution was to customize fromJSON, which I did and worked fine until I upgraded to Spine 1.2.0 recently.

The server I'm working with returns data in the following format:

{
  status: 200,
  message: "",
  data: [
    { 
      // serialized model 
    },
    ...
  ]
}

When calling code like:

m = Model.create( id: 1, status: "STATUS_ONE"  )
m.status = "STATUS_TWO"
m.save()
// Here, once the ajax call completes, m.status == 200 ie. the top level status key from the response

What would be the preferred way to handle this?

looks like the problem may be that model collect refresh uses fromJSON while instance refresh uses load.

So, after some fiddling around, I was able to fix it by doing the following:

PatchModelSave =
  included: ->
    if _.isFunction(@::ajax)
      @::ajax = ->
        singleton = new Spine.Ajax.Singleton(this)
        _recordResponse = singleton.recordResponse
        singleton.recordResponse = (options) ->
          (payload, status, xhr) ->
            datum = payload.data[0] # Insert appropriate unpacking logic here
            _recordResponse(options)(datum, status, xhr)

        return singleton

and then I can patch my models with:

class TestModel extends Spine.Model
  @include PatchModelSave
  ...

Seems to work so far, but if there is a cleaner solution I'd take it :)

What @aeischeid said is exactly right. Model.prototype.refresh is using load instead of fromJSON.

The issue was actually in recordResponse Pull Request 541 just re-adds the call to fromJSON that was removed.