Author: admin

This is the second article of the EcmaScript 6 niceties serieES6 also known as ES2015 brought a truck-load of new features and structures into Javascript and renewed the language as we knew it. This serie will highlight a few of the ES6 niceties you might find useful in your next Javascript project.
Today’s article is about those funny dots; rest- and spread-operator.

When looking at ES6 code for the first time you’ll probably notice the usage of three dots which you haven’t seen in any code written in Javascript’s earlier standards (<= ES5).
These three dots don’t necessarily do the same job, as there are two operators using that three-dot-syntax.

Rest operator

“The rest” can be assigned to a variable, using the rest-operator. Look at these rest-arguments:

function replace(string, ...replacements) {
  // return another string;
}
function subtract(...numbersToSubtract) {
  return numbersToSubtract.reduce((sum, next) => sum - next);
}
subtract(10, 1, 2, 3); // 4

Note that the rest operator must be a function’s last parameter!

Spread operator

The spread operator is sort of the opposite of the rest-operator: It takes an array of values, and turns it into ‘something else’ which uses comma-seperation. This might sound a little foggy, but these examples will clearify this:

// function calls
function combine(...numbers) {
  return subtract(...numbers) + add(...numbers);
}
combine(10,1,2,3); // 4+16=20

// assignments
const x = [1,2,3]; // 1,2,3
const y = [...x,4,5,6]; // 1,2,3,4,5,6
const z = [4,5,6,...x]; // 4,5,6,1,2,3
// assignments that converts Set and Map to an Array
let set = new Set([1, 2, 3, 3, 3, 4, 5]),
    array = [...set]; // [1,2,3,4,5];
let map = new Map([ ["name", "Sjoerd"], ["age", 40] ]),
    array = [...map]; // [ ["name", "Sjoerd"], ["age", 40] ]

// destructuring
const [a,b,...z] = y
a===1
b===2
z===[3,4,5,6]

Nearby future

The last example is called destructuring. In ES6 you can destructure ‘iterables’ (Array, Map, Set) and objects.

const { name, age } = { name: 'Sjoerd', age: 40, isDeveloper: true }

But you can’t destructure an object using the spread-operator. That could be so useful, especially working with React JS, where you find yourself often extracting values from props and state object literals.

But that is coming our way; Object Rest Spread proposal is in stage 4 in the ECMAScript approval process.
Using this Babel plugin enables you to use it now already.

const { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }
x===1
y===2
z==={ a: 3, b: 4 }

In React practice

let props = {};
props.foo = x;
props.bar = y;
const component = <Component {...props} />;

const props = { foo: 'default' };
const component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'
0

Hele december måned i år vil sejKo ikke være tilgængelig.
Vil du have udarbejdet noget som ikke kan vente indtil efter nytår, kontakt venligst sejKo i god tid 🙂

Ved nødstilfælde send venligst en SMS til 60 63 28 40.

0

Even though there are webservers out there serving static files better than Apache (like NginX), sometimes “you’re stuck” with Apache, or just don’t really care about a few milliseconds performance improvement.
OK, so you’ve got a single page application (a single HTML file with Javascript doing the heavy work) and you want to have it served by an Apache webserver. Your web-app probably has a few routes, and it probably works fine accessing the routes from the app’s starting point.
Example: myapp.com/inbox/incoming/123

But you want your app, to be accessible by “deep-links” too; in other words access myapp.com/inbox/incoming/123 directly. By default Apache will try and look up the directory /inbox/incoming/123 in your filesystem and tell the user there’s no such thing: 404.

You’ll have to tell Apache to rewrite everything to the index.html page, and let the single-page-application handle the routing. You do that like this:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

This is the first article of the EcmaScript 6 niceties serie. ES6 also known as ES2015 brought a truck-load of new features and structures into Javascript and renewed the language as we knew it. This serie will highlight a few of the ES6 niceties you might find useful in your next Javascript project.
Today’s article is about arrow functions.

Arrow functions have a different syntax than traditional Javascript functions (using =>), but they’re not just a shorthand notation; they behave differently in a few ways. I’ll show you a few common examples of when and how to use those functions, compared to Javascript prior to ES6.

Arrow function syntax – pretty short!

Look at the following piece of code. Here you see the arrow function assembling the tradition Javascript function. You can see the syntax is rather short, and you’ll see its variations get shorter and shorter 🙂

var es5Function = function(a,b) {
    return a + b;
};
let es6Function = (a,b) => { // rather similar to es5Function
    return a + b;
};
// note implicit return
let es6FunctionShorthand = (a,b) => a+b;
let es6DamnShort = y => y+2;

console.log( es5Function(1,2) ); // 3
console.log( es6Function(1,2) ); // 3
console.log( es6FunctionShorthand(1,2) ); // 3
console.log( es6DamnShort(1) ); // 3

As anonymous function

In Javascript you’ll be using anonymous function more than often 🙂 – they’re all over the place! Arrow functions can be quite handy right here, because of their short syntax and their different behavior. Let’s start rather simple, an event handler:

function doSomething() {
    console.log("Do something");
}
myButton.addEventListener('click', doSomething, true);

Here the function doSomething is used as an event-handler, and can be (re)used by other code.
Every now and then, you first need to take care of some things in a handler before you start calling reusable code. Sometimes the reusable function expects other parameters or you need to do / check something with the given arguments. For example with the event argument:

/* ES <= 5 */
myAnchor.addEventListener('click', function(event){
    event.preventDefault();
    doSomething();
}, true);

/* ES6 */
myAnchor.addEventListener('click', event=>{
    event.preventDefault();
    doSomething();
}, true);

Nothing new happened here, but your code gets a lot cleaner.
Remember how short arrow functions’ syntax can get. Imagine how much cleaner the following code becomes compared to its ES5 counterpart:

function doX(x){
    console.log(`Do ${x}`);
}

myButton.addEventListener('click', ()=>{
    doX("something");
}, true);
// it can get very short!
myButton.addEventListener('click', ()=>doX("anything"), true);

Doesn’t bind ‘this’

So far arrow function just makes your code cleaner, but still function as always. One of the main new behaviors you’ll get to use a lot is that it doesn’t (re)bind this.
Apart from when your using a callback for jQuery.each you’ll be using a workaround if you need to access this from within your (anonymous) callback / event-handler function. Often by declaring something like ‘var that = this;‘ before creating the anonymous function, and use that in stead of this.
Compare these two examples:

/* ES &lt; 5 */
var ES5Clickers = {
    init: function() {
        this.myButton = document.getElementById("butt");
        this.myAnchor = document.getElementById("link");

        this.myButton.addEventListener('click', this.doSomething, true);
        var that = this;
        this.myAnchor.addEventListener('click', function(event){
            event.preventDefault();
            /* this.doSomething(); // this.doSomething is not a function */
            that.doSomething();
        }, true);
    },
    doSomething: function() {
        console.log("ES5Clickers: Do something with this");
    }
};
ES5Clickers.init();

/* ES6 */
const ES6Clickers = {
    init() {
        this.myButton = document.getElementById("butt");
        this.myAnchor = document.getElementById("link");

        this.myButton.addEventListener('click', this.doSomething, true);
        this.myAnchor.addEventListener('click', (event)=>{
            event.preventDefault();
            this.doSomething(); // is all good now!
        }, true);
    },
    doSomething() {
        console.log("ES6Clickers: Do something with this");
    }
};
ES6Clickers.init();

Lambda

The short notation variations and implicit returns makes lambda kinda work a breeze:

const x = [{name:"Jane", age:20}, {name:"John", age:30}];
const y = x.map(z=>z.name); // return name of each object into the new array
console.log(y); // ["Jane", "John"]
0

Being able to extend classes is the key to powerful programming. PHP provides you all the tools you need to obtain rich and extendible classes. But sometimes you find yourself using the wrong tool.. Look at this very simple class:

class Post {
    const TABLE = 'posts';
    const TYPE = 'post';

    static public function all() {
        $select = "SELECT * FROM `%s` WHERE `type` = '%s'\n";
        echo sprintf($select, self::TABLE, self::TYPE);
    }
}

Post::all();
// SELECT * FROM `posts` WHERE `type` = 'post'

Look at the class constants TABLE and TYPE and you can almost feel what our next subclass will look like, and how minimalistic it will be:

class Comment extends Post {
    const TYPE = 'comment';
}

Comment::all();
// SELECT * FROM `posts` WHERE `type` = 'post'
// ^ is not what we meant...

Though the intentions are good, the result is unwanted: we want to select all from posts where type is ‘comment’, not ‘post’.
That is the blame for using ‘self’ to obtain the class constants. ‘self’ Refers to current class it is defined in, which is not the inherited class. But we don’t want to rewrite all the methods – that misses the point of all this. Using ‘static public $TABLE’ as property is an option, but why not use class constants now that PHP provides them.

A lot of people use ‘self’ to refer to class constants or static methods, but as soon as you start inheriting such class (often classes are coded without the intention to inherit them at some stage), this issue comes up.

We will have to use ‘late static binding’ in stead of ‘self’, simply by using ‘static’, which is computed using runtime information. Now take a look at the next example:

class Post {
    const TABLE = 'posts';
    const TYPE = 'post';

    static public function all() {
        $select = "SELECT * FROM `%s` WHERE `type` = '%s'\n";
        echo sprintf($select, static::TABLE, static::TYPE);
    }
}

Post::all();
// SELECT * FROM `posts` WHERE `type` = 'post'


class Comment extends Post {
    const TYPE = 'comment';
}

Comment::all();
// SELECT * FROM `posts` WHERE `type` = 'comment'
// ^ now that's just what we want

Now we’re selecting all from posts where type is ‘comment’!
And if you explicitly want to call the class you inherited from (perhaps in a constructor for doing some logics) you use ‘parent’ in stead, as here on the ‘save’-method:

class Post {
    static public function create() {
        return new static();
    }
    public function save() {
        echo "Inserts into the `posts` table\n";
    }
}

class Chat extends Post {
    public function save() {
        parent::save();
        echo "Inserts into the `post_recipient` table\n";
    }
}

Chat::create()->save();
// Inserts into the `posts` table
// Inserts into the `post_recipient` table
0

SejKo takker hermed alle sine kunder for et godt samarbejde dette år, og ser frem til at fortsætte det i det nye år.

Men inden vi når dertil ønsker sejKo en glædelig Jul!

PS: Der er julelukket mellem Jul og Nytår, for nødstilfælde send en SMS til 60632840

Det sidste stykke tid og de næste mange måneder frem arbejder sejKo på youSees platform for mobiltelefoni. SejKo er hyret igennem DBA Consult til TDC Group, som full-stack developer. Det indeholder både front- og backend arbejde på platformen der styrer administration, support, webshop, selvbetjening og API’erne.

0

Incendium ApS’ kunder som bruger platformen IncidentShare, kan nu live-streame ‘secured video’ med deres Android mobil / tablet via den nye IncidentShare app, udviklet af SejKo.
Incendium efterstræber at gøre deres komplicerede tjenester så enkele som muligt at betjene. Denne mobil app henter streaming konfigurationen, via et kundelogin til IncidentShare platformen, hvorefter man kan streame (bonded) video til ens egen konto. Appen oplyser den aktuelle bitrate, om streamet er bonded m.v.

Appen er udviklet i Java som ‘native Android app’.

incidentshare-android-devices

0

Hele sidste uge har sejKo haft fornøjelsen af erhvervspraktikanten Thomas Stanley Andersen.
Når jeg siger fornøjelsen, er det fordi Thomas har været meget engageret; Vil gerne lære nye ting indenfor kodning, oveni er han meget hurtig til at tage det til sig! Også de små opgaver han fik, løste han på ingen tid. Tak til Thomas – det var en fornøjelse at have dig!

Sparekassen Thy har valgt altid at være ved kundens side, via en ny mobil app. SejKo har leveret en iOS og Android app til både tablets og telefoner.

Appen giver direkte kontakt til ens rådgiver, og mulighed for at følge med i nyheder og begivenheder.
Alle data og push-notifikationer kan Sparekassen Thy styre fra platformen, hvor de også redigerer deres hjemmeside.

Teknisk er appen bygget som hybrid app, som gør det muligt at målrette både iOS og Android platformene fra en fælles kodebase – hvor man ellers udvikler to vidt forskellige apps; en til hver platform. Dette gavner både udviklingsprocessen og vedligeholdelsen af appen. Både i tid, pengene og projektstyring – da man ikke behøver at arbejde med forskellige udviklings teams.
Kodebasen er udviklet i det robuste framework, Ember.

Sparthy app, kontakt

Sparthy app, pushnotifications

Sparthy app på smartphone og tablet

Download appen Sparthy på Apple AppStore eller Google Play.