wiki:NagareTutorial3

Version 4 (modified by crumble, 7 years ago) (diff)

--

Nagare Tutorial, learning concepts

In MVC frameworks, clicking on html elements can perform actions the following way:

  1. Click on an active element (link, button, etc.) calls an URL,
  2. One way or another, the URL is mapped to the controller,
  3. The controller decides to do the action and to pass data to the view.

With Nagare, things are different, actions are directly mapped to active nodes of a DOM tree, let's see how it works.

Part3, add actions

  1. Add active nodes into DOM tree:

Change the view on our Counter class to add html links (a tags):

...
@presentation.render_for(Counter)
def render(counter, h, *args):
    h << h.div('Value: ', counter.val)
    h << h.a('++')
    h << '|'
    h << h.a('--')
    return h.root

In the upper exemple, we use the lshift operator to append nodes to the renderer and finally return renderer root. It is much more readable than to create and return a complex DOM tree.

  1. Bind action to active nodes:

As active nodes ,`a` nodes have a special method call action that is used to bind action to a DOM node. An action can be any callable and in particular a class method.

...
@presentation.render_for(Counter)
def render(counter, h, *args):
    h << h.div('Value: ', counter.val)
    h << h.a('++').action(counter.increase)
    h << '|'
    h << h.a('--').action(counter.decrease)
    return h.root

That's it! Now, you can play with your counter at http://localhost:8080/tutorial.

  1. How does it work?

Nagare handles request in two phases:

  • Phase1: callbackmanager finds action from its id and execute it on the right state of the application. That way object graph is modified and a new snapshot is created,
  • Phase2: presentation service generates and serialize a DOM tree for current object graph. HTML page is redisplayed in the browser.

If you look closely at generated URL, you will see something like: ?_s=2171996978143275&_c=00011&_action480534548. Each URL parameter meaning the following:

  • _s: id of the session created for the application,
  • _c: id of the snapshot of the state of the application,
  • _actionxxx: id of the callback to call.

As you can see URL are non-significative, this improves security in comparison of the MVC's way of doing it. Of course, you DON'T HAVE to use significative URL but you totally CAN if you NEED it (see RestfulUrl). You just don't have to bother with URL when doing something like the third step of a wizard or a shopping basket.

  1. Back and Fork

Start with a counter at 0, do ten times '++' and see what happens when you use you browser back button 4 times. What do you expect when doing '++' now? 11? 7?

Open a new tab on '--' link, you get one tab with a value of 7 and one tab with a value of 6. Play with the 2 counters, that's right, you have 2 different counters!

Go to part 2 of this tutorial | Go to part 4 of this tutorial