Wednesday, December 5, 2012

Debugged Cargo-Coded Dart

‹prev | My Chain | next›

Sick. Stomach bug. But the gods, they must be appeased...

Hopefully this will be a quick one. Last night I was able to get my newly rebased mvc-sync working with localStorage—at least for reading from localStorage. It turns out that I had a bit of difficulty writing to that storage, so I hope to clean that up tonight.

Mercifully, it does turn out to be a simple problem. I think that I had copied the POST/create handler from a different branch because this was never going to work in this old, callback riddled version:
main() {
  HipsterSync.sync = localSync;
  // ...
}

localSync(method, model, {options}) {
  // ...
  if (method == 'post') {
    var collection = model.collection,
        attrs = model.attributes;

    if (attrs['id'] == null) {
      attrs['id'] = "${attrs['title']}:::${attrs['author']}".hashCode.toString();
    }

    collection.create(attrs);

    var json = window.localStorage[collection.url],
        data = (json != null) ? JSON.parse(json) : {};
    data[attrs['id']] = attrs;
    window.localStorage[collection.url] = JSON.stringify(data);
  }
}
The problem is that collection.create(). I am in the middle of synchronizing data between the client code and the datastore (localStorage in this case, but normally a RESTful backend). While I am in the middle of synchronizing data, I cannot call collection.create() because that will start another synchronization event, resulting in an endless loop:


Fortunately, the problem is an easy one to solve. I just need to convert that to a collection.add():
localSync(method, model, {options}) {
  // ...
  if (method == 'post') {
    // ...
    collection.add(attrs);

    var json = window.localStorage[collection.url],
        data = (json != null) ? JSON.parse(json) : {};
    data[attrs['id']] = attrs;
    window.localStorage[collection.url] = JSON.stringify(data);
  }
}
With that, I can save data in localStorage while reading continues to work just fine:


I really cannot figure out where that collection.create() originated. Even in the most recent versions of Hipster MVC, a collection create will result in a data sync occurring. Oh well, I am not going to worry too much tonight. Instead, I take this as my cue to go back to sleep.


Day #590

No comments:

Post a Comment