Hello World with FlightJS

October 5, 2015

flightjs

For those of you that don’t know, Twitter has it’s own Open Source JavaScript Framework. It’s called FlightJS and it’s pretty cool (I may be biased).

It’s pretty easy to get started with and the documentation is great, but here’s a quick “Hello World” so you can hit the ground running.

Installation

For this example, let’s use the CDN hosted libraries for Flight and it’s dependency, jQuery. We’ll start with a simple HTML page.

<!DOCTYPE html>
<head>
    <title>Hello World with FlightJS</title>
</head>
<body>
    <div id="hello">Click Me!</div>
    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <!-- Flight release -->
    <script src="http://flightjs.github.io/release/latest/flight.min.js"></script>
    <!-- Your script -->
    <script src="js/script.js"></script>
</body>

Your First Component

Inside that script.js file, let’s do something like this.

/* Component definition */

var Hello = flight.component(hello);

function hello() {
  this.sayHello = function() {
    alert('Hello World!');
  },

  // after initializing the component
  this.after('initialize', function() {
    this.on('click', this.sayHello);
  });
}

/* Attach the component to a DOM node */

Hello.attachTo('#hello');

Now load the page and click on the text!

Understanding Components

Components are fairly simple. This one only consists of four parts.

The definition

var Hello = flight.component(hello);

function hello() {

Some number of methods

this.sayHello = function() {
    alert('Hello World!');
}

Event Listeners

this.after('initialize', function() {
    this.on('click', this.sayHello);
});

DOM Attachment

Hello.attachTo('#hello');

Conclusion

That’s really all there is to it. We make our sayHello method, wrap it in a Flight component, bind it to a click listener and attach it to the DOM.

Stay tuned for a lot more FlightJS tutorials!