views:

787

answers:

3

I'm starting to get my head around node.js, and I'm trying to figure out how I would do normal MVC stuff. For example, here's a Django view that pulls two sets of records from the database, and sends them to be rendered in a template.

def view(request):
    things1 = ThingsOne.objects.all()
    things2 = ThingsTwo.objects.all()
    render_to_response('template.html, {'things1': things1, 'things2': things2})

What might a similar node.js function look like?

A: 

That might be:

var view = function(request) {
    var things1 = Things.objects.all();
    var things2 = Things.objects.all();
    render_to_response('template.html', { things1: things1, things2: things2 });
};

Or if you have asynchronous API:

var view = function(request) {
    var model = {};
    Things.objects.getAll(function(things1) {
        model.things1 = things1;
        if(model.things2) {
            render_to_response('template.html', model);
        }
    });
    Things.objects.getAll(function(things2) {
        model.things2 = things2;
        if(model.things1) {
            render_to_response('template.html', model);
        }
    });
};
Vytautas Jakutis
Is that a guess? Since all IO in node.js is non-blocking, I'm thinking you'd need to define callbacks for Things1, Things2 and render_to_response...
Chip Tol
It is just a translation to JavaScript syntax :] It is more efficient to access database asynchronously, but I do not know your API :} I'll edit my answer and add another, asynchronous variant.
Vytautas Jakutis
Thanks for the code, Vytautas. In this case the API is node.js, which is at http://nodejs.org/. So, it's not an abstract question, but related to that toolset directly.
Chip Tol
nodejs.org is not a web framework, it is just a javascript runtime platform, so you probably should not expect MVC methods like render_to_response or Things.objects.get to be part of the API.
Vytautas Jakutis
+3  A: 

I've found http://howtonode.org/ to be a big help in getting me up-to-speed.

Chip Tol
+1  A: 

http://expressjs.com/

한국인