komagata
komagata

Reputation: 51

Useful nodejs library for a Rails JSON API

I'm making a Titanium Mobile app.

It's relation with Rails JSON API.

I must make some model objects for Rails model objects. It's too annoying. (paging etc.)

I want to know javascript library that mapping javascript model class to Rails model class. (like a model in backbone.js)

I searched npm registory, but I can't find it.

Upvotes: 0

Views: 177

Answers (1)

Matt Sieker
Matt Sieker

Reputation: 9635

If you're not set on Backbone, you could look at Knockout.js with the mapping plugin. While you still have to create classes for each model, you don't need to fully populate them. A pattern I've been using a lot lately for this:

function SubModel(data, parent){
   var self = this;
   ko.mapping.fromJS(data,{},this);

   //Various computed items and functions to work with this model
}

function Model(data, parent){
   var self = this;
   ko.mapping.fromJS(data,{
      subModel:{
         create: function(options){
            return new SubModel(options.data, self);
         }
      }
   }, this);
   //Various computed items and functions to work with this model
}

You then take the JSON you get from the service, do a new Model() and pass it the data, and Knockout will create all the various properties on that class from the JS. Any nested objects can be handled in the same manner as the SubModel mapping, down to an arbitrary depth.

In addtion, the mapping plugin also includes a toJS function, that will allow you to re-serialize a model that has been created from fromJS back to JSON.

Upvotes: 1

Related Questions