Close

Entries with tag javascript .

Learn ES6 Today with Vaadin Elements - Part 3: Arrow Functions

In this short segment of our guide to ES6, you’ll learn how to use the Arrow function syntax to create cleaner code.

We will be referencing the example we wrote in the previous guides. You can read the first and second parts of this blog series here:

  1. Part 1: Promises
  2. Part 2: The Fetch API

Arrow functions

Our ES6 guide is all about making code simpler and more readable, so let’s talk about ES6’s new Arrow function syntax. Arrow functions let you write functions with straightforward syntax. Arrow functions look like parameters => expression. The result of expression is then returned. This skips writing both function and return. That may not seem like much, but it makes writing functions and callbacks so much clearer.

Let’s take a look at a few quick examples.

// ES5 way
var doubleES5 = function(x) {
  return x * 2;
}

var addES5 = function(a, b) {
  return a + b;
}

// ES6 way
var doubleES6 = x => x * 2;

var addES6 = (a, b) => a + b;

As you can see, writing arrow functions is a breeze. If you need to do more work in a function, then you can enclose the right side in curly braces to make a regular block expression. In this case, the return is no longer implicit and does need to be called.

var doWork = (x, y, z) => {
  // ... do stuff ...
  return someResult;
}

Caveat

One thing to note is that arrow functions do not create their own context, so this inside of an arrow function is the same as the enclosing scope. While on the whole, this makes function code more clear, this can lead to trouble if you’re not expecting it.

var scope = this;

var container = {
    classicSyntax: function() {
        console.log(this === scope); // False!
    },

    arrowSyntax: () => {
        console.log(this === scope); // True!
    }
}

container.classicSyntax();
container.arrowSyntax();

You can learn more about arrow functions at this great article on Mozilla Hacks.

Cleaning up our code

Now we’ll finish tidying up our code with the new arrow function syntax. Follow along at jsbin here.

Arrow functions are particularly useful for cleaning up Promises and then blocks, so we can shorten getJSONPromise even more.

function getJSONPromise(url) {
  return fetch(url).then(response => response.json());
}

I’ve similarly updated the rest of the code to use arrow functions, which you can see in the finished code.

Browser support

Arrow functions are available in all modern browsers, with the exception of Internet Explorer and Opera Mini.

Conclusion

Arrow functions is just another way the evolving web platform is making coding simpler. When the constructs you use are streamlined, then your code itself will be clearer and understandable.

In the next episode of our series on ES6 we’ll cover a few more advanced features of the platform.

Learn more about <vaadin-grid> and Vaadin Elements

Vaadin and AngularJS - happy together

You certainly read and hear a lot about JS frameworks, foremost AngularJS, and as a Vaadin developer you might just wonder what to make of it: ignore it? (Would be a shame, there is great stuff out there.) Jump ship altogether? (Would be a shame, too - you’d loose Vaadin.) But fortunately, it’s not really Vaadin or AngularJS - it’s rather Vaadin AND AngularJS.

There is an add-on available that lets you combine the best of Vaadin and AngularJS: Vaangular

Some reasons why you might want to do that:

  • mix and match skill within your team
  • increase responsiveness with bad network connection (by doing client-side logic)
  • reuse existing AngularJS-based assets
  • have an alternative to custom GWT development

And: you don’t have to do any GWT development (and no REST-backend-HTTP-calls either - because you have Vaadin for that, haven’t you?).

Here’s an example that uses Vaangular to increase responsiveness. Imagine you want to provide a weather forecast with a slider to select the time and get some more details: 

Slider with clock times and temperature for each time - i.e. a weather forecast

For a maximal user experience, even for users with slow network connection, you'll want to minize the server roundtrips. This would be a perfect task for your client side developer, but he/she is probably more keen to use AngularJS than GWT.

To include an AngularJS-based slider view into a Vaadin UI, you have to include the Vaangular add-on and follow these steps (we have the full code available on Github)

First: create an HTML fragment with AngularJS bindings:

<div ng-controller="WeatherController">
    <div ng-bind-html="content()"></div>
    <input type="range" min="0" max="{{userState.times.length-1}}" 
            step="1" ng-model="sliderPos" />
    <div>
        <div ng-repeat="t in userState.times" 
                ng-click="moveSlider($index)">
            <div>{{t}}</div>:00
        </div>
    </div>
</div>

Second: create a matching AngularJS controller (and a unit test, please! – you can download ours) 

angular.module('weatherModule', ['ngSanitize'])
.controller('WeatherController', function($scope, $connector, $sce) {
    $scope.sliderPos = 0;
    $scope.content = function() {
        var res = $scope.userState.entries[$scope.sliderPos];
        return $sce.trustAsHtml(res);
    };
    $scope.moveSlider = function(val) {
        $scope.sliderPos = val;
    };
});

You’re almost there. All what’s left is to write a Vaadin component that’s derived from de.akquinet.engineering.vaadin.vaangular.angular.NgTemplate or de.akquinet.engineering.vaadin.vaangular.angular.NgTemplatePlus. You can set weather data like this: 

public void setData(int[] times, String[] entries) {
    validateParameters(times, entries);
    this.times = times;
    this.entries = entries;
    setUserState("times", times);
    setUserState("entries", entries);
    markAsDirty();
}

Everything put in via setUserState is forwarded to AngularJS. 

Add your component to the UI, fire off the server – and enjoy.

Of course, you can also submit data from the client to the server (both immediate and deferred) and call methods on the server. You can also apply Vaadin style classes to HTML generated by AngularJS – it’s all up to you

See more detailed instructions and more extensive examples

(also available in German)

Oliver Damm, Axel Meier, Sebastian Rothbucher
Oliver Damm, Axel Meier and Sebastian Rothbucher are Vaadin & Web developers and trainers working for akquinet AG in Hamburg, Germany. When not watching FC St. Pauli play or chilling at Lake Alster they craft business web applications – with Vaadin, of course.

Vaadin, JS and DOM initialization order

As we all probably already know, one of the great new and interesting features of Vaadin 7 is the easy integration of any JavaScript component. No need to write wrappers between GWT and JavaScript anymore, just a simple connector and a state class and you have the freedom to use any kind of JS thingies with your Vaadin application.

But then there are some things that won’t work with Vaadin like they would work with traditional HTML pages. For example, jQuery’s $(document).ready() can’t be used in most cases since it is triggered before Vaadin has actually loaded its components.

Gauges and canvases

I came across this issue when I had to use the Gauge component developed by Mykhailo Stadnyk. The problem was that it requires a canvas element whose DOM id has to be given to it when it is initialized. Therefore you have to be sure that such element exists before the component is drawn.

So I somehow needed to find a way to create a canvas element and then make sure that it is rendered before the gauge. In order to make the system flexible, it was clear that the DOM id must be parameterized so that it can be set from the server-side. A hard-coded id would cause a load of problems, including the fact that there could be only one gauge per page.

The goal was to create a component that allows you to set the DOM id of the canvas element on the server-side and then implement the JavaScript connector so that it creates the corresponding element with the given id.

The simple part: server-side

As expected, the creation of the server-side classes was the easy part. First I implemented the state object that in this case takes care of the synchronization of two variables: the DOM id used and the value of the gauge.

public class GaugeState extends JavaScriptComponentState {
    public int value = 0;
    public String domId;
}

Then I created the actual Gauge class. The @JavaScript annotation is used to load the required JavaScript files: gauge.js containing the Gauge library and gauge_connector.js that is used as a bridge between the library and this class.

Because the id of the canvas element should be set only once, it is given in the constructor and can’t be changed afterwards.

@JavaScript({ "gauge.js", "gauge_connector.js" })
public class Gauge extends AbstractJavaScriptComponent {
    public Gauge(String domId) {
        getState().domId = domId;
    }
    public void setValue(int value) {
        getState().value = value;
    }
    @Override
    protected GaugeState getState() {
        return (GaugeState) super.getState();
    }
}

A bit harder part: JavaScript connector and DOM manipulation

The next step was to create the client-side connector, gauge_connector.js, that receives the parameters from the GaugeState class and applies them to the actual JavaScript component. As a side note, the initialization of the connector can be compared to jQuery’s $(document).ready() function: it is called when the required ‘surroundings’ are ready for the component.

The first thing the connector has to do is to create the canvas element and then append it to the DOM. Luckily, at this point, Vaadin has already created a div element for the component. Therefore we can just create a canvas element, get a DOM id for it from the state object and apply the final result to the pre-existing element. After that the actual Gauge object can be created, giving it the same id that was used with the canvas element. Then the gauge can be drawn.

Also, onStateChange() function was needed so that the value of the gauge can be set from the server-side.

org_vaadin_blog_Gauge = function () {
    var domId = this.getState().domId;
    var canvasElement = document.createElement('canvas');
    canvasElement.setAttribute('id', domId);
    this.getElement().appendChild(canvasElement);
    
    var gauge = new Gauge({
        renderTo: domId,
        value: this.getState().value
    });
    gauge.draw();
    
    this.onStateChange = function () {
        gauge.setValue(this.getState().value);
    };
};

As a result, we can now have two (or even more!) beautifully animated gauges on one page.

Links and afterthoughts

If you want to, you can check out the example project from GitHub. It is also up and running in case you just want to see the gauges in action. I guess I don’t have to mention that the Gauge is a fully customizable library that has many more settings than these two used in this example.

Now that I think about it, you could probably make this even better by making the id generation automatic. For example, using a pre-defined word with a static counter would be one way of doing this.

After all, isn’t it a bit against Vaadin ideology that the user has to care about things like DOM ids?


Tapio works at the Vaadin team helping our customers in building solutions on top of Vaadin Framework. Inspiration for this blog post originates from a support question.