A minimalistic MVC experiment in TypeScript

I was inspired by dom-o, a minimalistic javscript library to create markup, by jed. And wanted to play some with it so I ended up making a little TypeScript MVC-experiment with it.

With dom-o it’s easy to create markup with regular javascript functions:

var markup = DIV(
    H1("Sample"),
    DIV({ id: "myView" }));

$("#body").html(markup);

The resulting markup is:

<div>
  <h1>Sample</h1>
  <div id="myView"></div>
</div>

I begun with creating a dom-o TypeScript definition file to get some intellisense to it. Next I created a simple class with a render function:

class ViewRenderer {
    view: any;
    constructor (view: any) {    
        this.view = view;
    }
    render($el:any) {
        var renderedView = (typeof (this.view) == "function") ? this.view() : this.view;
        $el.html(renderedView);
    }
}

var view = new ViewRenderer(()=>P("date and time : " + new Date());
view.render($("#someId"));

And then I added a model to the view and made the ViewRender render the view with the model as a parameter.

var personView = (model: PersonModel) =>
    DIV(model.firstName)

MVC style helper
Since the view is a javascript function it’s easy to create helpers:

var inputControl = (label: string, id: string, value:()=> string) =>
    DIV(LABEL(label + ": "),
    INPUT({ id: id, value: value() }),
    BR());

Which in a view can be called this way:

var personView = (model: PersonModel) =>
    DIV(
        inputControl("First name", "firstname", () =>model.firstName),
        inputControl("Second name", "secondname", () =>model.secondName),

The result
Long story short : after some play I got a small (25 locs) ViewRenderer class which ties together model, view and controller. You find it together with a sample in the ViewRenderer.Ts github repo.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s