Search code examples
node.jsoopbackbone.jsmodels

How to reproduce Backbonejs Models & Collections in node.js server side


I'm a newbie with nodejs but I am excited about the possibility of a common language and idiom between client and server.

Does anyone know of a nodejs framework that provides the same OO idiom and class functionality for Models that we're used on the client with backbonejs? I find it jarring to switch between backbone models and collections and hand-rolled javascript classes in node.

Controllers are replaced by emitters and callbacks, and of course there are no views, but am I wrongheaded to want a consistent OO paradigm for Models client and server side? Should I be using a database-agnostic OOP to meet that objective such as Redis?

If this question is too vague for SE feel free to shut me down.


Solution

  • When working with Backbone.js you should have a bunch of models on the client, those get fetched from the server and updated to the server via REST api (CRUD). The client is responsible for the MVC and the server just answers a bunch of simple queries, deletes and updates.

    This means that the client will probably contain code for:

    • Models
    • Views
    • Router
    • templates (HTML)
    • Collections
    • Utils
    • 3rd party Libs

    The server will have:

    • Schemas (for the models that need to be stored in DB)
    • Models
    • Utils
    • Server code for restful api response (e.g. express.js)
    • libs

    So... what code should be shared between the client and the server? some utils, maybe the models.... (Although I think that models code should not be shared)

    Basically although we (the developers) are all excited with sharing code between client and server, The use case and roles and responsibilities doesn't really require this coupling. (at least that is what happened to me)

    By the way, there are some exceptions where you would like to implement the same MVC on the server for fast rendering and search engine compliance, airBnb are doing this with backbone and node. and they will open source there solution once they stabilize the API

    EDIT:

    From my experience Backbone Models are pretty thin Data only objects ( and some validation code). The viewers observe them and change them, so most of the code goes in there. I think that in this case decoupling the code from the server to the client is a good design decision, it allows you to play with your DB schemas without changing the client.

    But of course this can be different in other use cases...

    Regarding your actual question:

    You can check out airBnB project Rendr: (https://github.com/airbnb/rendr)

    Rendr is a small library from Airbnb that allows you to run your Backbone.js apps seamlessly on both the client and the server. Allow your web server to serve fully-formed HTML pages to any deep link of your app, while preserving the snappy feel of a traditional Backbone.js client-side MVC app.