The Golf Web Application Server home roadmap1.0 help rss

A Simple Component

26 Dec 2009 - Micha Niskinsourcedownloaddemo

Golf components are reusable, self contained units from which the MVC views are built. Components are constructed from regular HTML, CSS, and JS. They are instantiated in your JS code and inserted into the DOM using jQuery.

This article goes past the simplistic Hello, World example, and demonstrates a simple MVC view and controller. The model is left as an exercise for a later article.

Create The Application Directory Structure

Before we can start writing components we must first create some directories that our app will need. We want our directory to look like this:

+ golf-example/
|-- controller.js
`-- components/
    `-- HelloWorld/
        `-- HelloWorld.html

When you have your app directory set up as above, open a terminal and change to the golf-example directory.

Give The Component Some HTML, CSS, And JavaScript

The component’s structure and behavior is defined in an HTML file, HelloWorld.html. This file is located in the HelloWorld directory and is where the HTML, CSS, and JavaScript for the component will be. If your component requires resources like images, for example, they would go in a directory named HelloWorld.res in the HelloWorld folder. For now we won’t worry about component resources, though.

Create the file components/HelloWorld/HelloWorld.html, with the following contents:

<div>
  <style type="text/golf">
    div.container {
      border: 1px solid red;
    }
  </style>
  <script type="text/golf">
    function() {
      $(".container").append("<h1>Hello, world!</h1>");
    }
  </script>
  <div class="container"></div>
</div>

Notice how the component HTML markup is acting as a sort of template, into which the content is inserted by jQuery. This is a powerful pattern. The Golf server’s JS proxy capability allows us to leverage this to the fullest. For now, though, our app is almost finished. All that remains is to write a simple controller.

Write The Controller

Create the controller.js file:

$.golf.controller = [
  { route: ".*",
    action: function(container, params) {
      container.append(new Component.HelloWorld());
    }
  }
];

Note the Component namespace that our component is in. This is true of all components. If we had created our component in the components/com/example directory instead of just the components directory, we would have needed to instantiate it like this:

new Component.com.example.HelloWorld()

But we’re keeping things simple for now. Okay! It’s time to test it out!

Test The Application In Dev Mode

Start up the Golf dev mode server, like this:

golf .

Then, open a browser and navigate to http://localhost:4653/golf-example/#/home/. You should see something similar to this:

blog comments powered by Disqus
Fork me on GitHub