Tuesday, March 29, 2016

Creating a Donation Widget with Flight Components

In this tutorial I will be teaching you the basics of Twitter's Flight.js by making a donation widget, which also uses Materialize for the front-end, and Stripe to handle the payments. We'll be covering Flight's main concepts and methods.

Flight is an event driven framework by Twitter. Based on components, Flight maps behaviors to DOM nodes independently. Unlike other popular frameworks, Flight doesn't prescribe a particular approach to how you render or fetch your data it is, however, dependent on jQuery. In its essence, Flight is all about events. These can be triggered by the DOM or by artificial triggers within other UI components. Flight is basically a framework for making frameworks. This might sound complicated, but while Flight isn't as 1-2-3 as jQuery, its learning curve is exaggerated and learning Flight could definitely improve your JavaScript skills.

Why Use Flight?

  • Write more readable jQuery.
  • Write re-useable components.
  • Use as much or as little of other libraries as you want.
  • A better structure for your code in general.
  • Supports and even prefers modular JS.

Readability: jQuery vs Flight

Let's say we're listening for a click and a hover on a button. Using jQuery you'd probably do something like this:

$('#button').on('click', function() {
  confirm('You clicked?');
});
$('#button').on('mouseover', function() {
  console.log('Oops');
});

But using Flight this all goes into one component.

var Button = flight.component(function () {
  this.log = function () {
    console.log('Oops!');
  }
  this.confirm = function () {
    confirm('You clicked?');
  }
  this.after('initialize', function(){
    this.on('mouseover', this.log);
    this.on('click', this.confirm)
  })
});

Button.attachTo('#button');

Of course, jQuery requires less code but, with Flight our code is structured a lot clearer. The events are two different threads in jQuery, but in Flight these are both contained within the same component. We can easily see that this component and the element it is attached to are listening for two events. But let's say we wanted to add that hover event listener 200 lines later in our code. Using jQuery, you'd probably add it at that point in your file. However using Flight we are almost forced to add it to the existing component.

I've made a template that includes everything you need to get started so you can get straight to coding. You can download it from Github or fork it on CodePen.

Want to make your own template? Just copy in these CDN's:

<script src="http://ift.tt/1hhKFa1"></script>
<script src="http://ift.tt/1qfoTcA"></script>
<script src="http://ift.tt/1doUtf9"></script>    

Making Your First Component

Flight consists of 'components'. Components are reusable blocks of code that stand alone within your application. Creating a component is a lot like creating an object constructor except that components cannot be changed or accessed after they have been initialized. Components can only communicate with your app through events. Either by triggering them, or listening to them.

Flight component's can be as simple or as complex as you like. In the example below we are only listening for a hover (mouseover) event on a button, and showing an alert when that happens.

var Button = flight.component(function () {
  this.alert = function () {
    alert('Oops!');
  }
  this.after('initialize', function(){
    this.on('mouseover', this.alert);
  })
});

Button.attachTo('#button');

This is obviously nothing jQuery couldn't do, and structuring your code like this may seem like a lot of effort now, but once you start using Flight for things other than hover events you will understand its benefits.
As long as you understand that it's listening for a mouseover event and triggering an inner function you're fine for now. I'll explain what the rest means later on in this tutorial.

Getting Started

If you are using the template, the form in your index.html file should look like this:

<form action="#">
    <input type="checkbox" id="accept" />
    <label for="accept">By proceeding your agree to our terms, which are completely unfair and well, not very real.</label>
    <br/>
    <button class="waves-effect btn" style="margin-top: 15px;" id="launch" disabled>Let's Go</button>
</form>

We want to enable the button when the check-box has been checked and disable it otherwise. Let's head over to our JavaScript code and create our first component.

var checkToEnable = flight.component(function () {
  // Magic
});

Each Flight component consists of a few different methods. Some of these are required, others are not. The first method we'll be adding is attributes(). The attributes() method contains one or more attributes. Attributes are scoped variables and / or arguments. Empty attributes (ones declared with a value of null), require a value to be passed to them when the component is initialized. Other attributes will use their default values unless instructed otherwise. Attributes are typically used to hold element references. Insert the following code into your component:

this.attributes({
    button: null 
});

The button attribute will serve as a reference to the button we want to enable. The next method we want to add is the initialize() method.

this.after('initialize', function () {
    this.on('change', this.enableButton); 
});

Flight components already define a default implementation of initialize() which we want to extend rather than overwrite, which is why we're using the after() method here. Inside of the callback function we've added an event listener. This will listen for a change on the element which the component will be attached to and consequently trigger the enableButton() function, which we'll create next.

this.enableButton = function (e) {
    var buttonEl = document.getElementById(this.attr.button);
    switch (e.target.checked) {
        case true:
            buttonEl.disabled = false;
            break;
        case false: 
            buttonEl.disabled = true;
            break;
    }
};

Continue reading %Creating a Donation Widget with Flight Components%


by Niels Klomb via SitePoint

No comments:

Post a Comment