Serenade.js



Serenade.js

0 0


Itera.SerenadeJsPreso

The Serenade.js presentation from March 7th 2013 at Itera HQ

On Github Itera / Itera.SerenadeJsPreso

Serenade.js

Hello World

var element = Serenade.view('h1 "Hello World"').render();
$("#slide2demo").append(element);
                    Run!

As you can see we are rendering a view, which returns a DOM element. We then insert this element into the body.

Model-View

var model = { name: "Anders" };
var element = Serenade.view('h1 "Hello " @name').render(model);
$("#slide3demo").append(element);
                    Run!

Now the render function takes a regular JavaScript object as its first parameter. We can access this data in the template.

DOM events and controllers

var controller = { say: function(element, model) { alert("Hello " + model.name) } };
var model = { name: "Anders" };
var element = Serenade.view('button[event:click=say] "Say hello"').render(model, controller)
$("#slide4demo").append(element);
                    Run!

The controller is the second argument to render. Event bindings are declared in the view, and when the view is rendered, the events are attached to the rendered elements. Since Serenade's render function returns an actual DOM element, as opposed to returning a string, you don't need to do anything else than inserting that element into the DOM for everything to just work.

Registering views

// We will probably want to save the view so that we
// can render it multiple times, just give it a name:
Serenade.view('hello_world', 'h1 "Hello " @name');

// And you can render it later, through the global Serenade.render function:
var element = Serenade.render('hello_world', { name: "Anders" });
$("#slide5demo").append(element);
                    Run!

Two way data binding

We can keep our templates in separate elements. #protip <script type="text/template"/> is nice.

input[type="text" binding=@name]
button[event:click=say] "Say hello"
                    

And use it in our code...

var controller = { say: function(element, model) { alert("Hello " + model.name) } };
var model = Serenade({ name: "Anders" });
var element= Serenade.view($('#template').text()).render(model,controller);
$("#slide6demo").append(element);
                    Run!

Of course there is much more to it. Visit serenadejs.org to learn more.