Tag: javascript

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'

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"]

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.

0

WooCommerce has an awful lot of hooks! Very useful if you want to customize a webshop without touching the WooCommerce core – so you’re safe when updating it. Check out the availability in the documentation!

Here’s an example:
In some occasions you want to do something extra with the WooCommerce checkout form. This could either be adding some HTML, or a while Javascript file just for this occasion, or something completely different.
You can use ‘woocommerce_after_checkout_form’ or ‘woocommerce_before_checkout_form’ from your plugin or (child-)theme.

function add_scripts_checkout() {
    wp_enqueue_script(
        'checkout-script',
        get_stylesheet_directory_uri() . '/includes/js/checkout.js',
        array( 'jquery' )
    );
}
function add_html_checkout(){
    $img_src = get_stylesheet_directory_uri() . '/img/certified-something.png'
    echo '<img src="'.$img_src.'"';
    echo ' class="certified-something">';
}

add_action( 'woocommerce_before_checkout_form', 'add_html_checkout' );
add_action( 'woocommerce_after_checkout_form', 'add_scripts_checkout');

As you can see, you can either output HTML straight away by echo’ing right before / after the markup of the checkout-form, or handle things programatically like enqueing a javascript file. This Javascript file will only be loaded wherever there’s a WooCommerce checkout-form present, and thus you can target those checkout forms directly with your Javascript functionality.

0

Hjemmesiden Støtnationalparkcenterthy.dk er skabt til at indsamle penge til Nationalparkcenter Thy, og formidle progressionen.

Støtnationalparcenterkthy.dk Støtte

SejKo har leveret denne ‘one-page’ hjemmeside (d.v.s. at man samler alt info på én side – men man stadig kan navigere til det via menuen) mens Thy Nationalpark selv har fyldt indhold på.
Hjemmesiden er udrustet med Sikkerhed-først-pakken mod eventuelle hackerangreb.

Her er hele hjemmesiden på én side; one-page

 

Støtnationalparkcenterthy.dk one-page

0

For a project I’ve been working on recently I needed to convert text, retrieved from an API, to HTML.
The text isn’t “mark-down” but does contain line-breaks, URLs, hash-tags etc. etc. Since there wasn’t any add-on or snippet doing exactly this, I decided to roll my own.
Now I want to share my ‘snippet’ (only one file) with you, so you hopefully can benefit from it too, or modify it if needed.

You can find it here on Github Gist

As you can see I’ve included my test-file as well. Download both files and place “text-2-html.js” into your “app/helpers” directory (and “text-2-html-test.js” into your “tests/units/helpers” directory).

Now you can use the helper like this:

{{text-2-html message}}

By default the helper converts:

  • new-lines (attribute “nl”)
  • URLs (attribute “url”)
  •  e-mails (attribute “email”)

When configured it also converts:

  • phone-numbers (attribute “phone”) — note: buggy!!
  • hash-tags (attribute “hashTagURLPrefix”)
  • mentions (attribute “mentionURLPrefix” and “mentionAtShown”)

Usage

Here are some examples to illustrate these options:

Handlebars template

basic:
{{text-2-html item.message}}

defining target:
{{text-2-html item.message target='_system'}}

convert phone-number, note this is somehow buggy:
{{text-2-html item.message target='_system' phone=true}}

hash-tags and mentions, twitter links:
{{text-2-html item.message hashTagURLPrefix='https://www.twitter.com/hashtag/' mentionURLPrefix='https://www.twitter.com/'}}

hash-tags and mentions, hiding the @-sign for mentions, facebook style
{{text-2-html item.message hashTagURLPrefix='https://www.facebook.com/hashtag/' mentionURLPrefix='https://www.facebook.com/' mentionAtShown=false}}

See full reference below

I must tell that the phone-number feature might act a bit buggy (that’s why it’s not a default feature); it does recognize must phone-number formats but also other numbers, intended for something else. Try and see if it works for your purposes, otherwise I might work on that one day.

Assume we have the following text:

Hey\nHow're ya doin'?\nSorry you can't get through.\nWhy don't you leave me your name, mine is @planetcrypton, and your number, mine is +4560632840, and I'll get back to you.\nDon't forget to visit http://www.wearedelasoul.com/\nMail me at plug2@reversed-yogurt.com #oldschool #plug1 #plug2 #plug3

With this in your Handlebars:

{{text-2-html item.message hashTagURLPrefix='https://www.twitter.com/hashtag/' mentionURLPrefix='https://www.twitter.com/'}}

Would result in the following HTML-output:
Hey<br>
How&#39;re ya doin&#39;?<br>
Sorry you can&#39;t get through.<br>
Why don&#39;t you leave me your name, mine is <a href=”https://www.twitter.com/planetcrypton” target=”_system”>@planetcrypton</a>, and your number, mine is <a href=”tel:+4560632840″>+4560632840</a>, and I&#39;ll get back to you.<br>
Don&#39;t forget to visit <a href=”http://www.wearedelasoul.com/” target=”_system”>http://www.wearedelasoul.com/</a><br>
Mail me at <a href=”mailto:plug2@reversed-yogurt.com”>plug2@reversed-yogurt.com</a> <a href=”https://www.twitter.com/hashtag/oldschool” target=”_system”>#oldschool</a> <a href=”https://www.twitter.com/hashtag/plug1″ target=”_system”>#plug1</a> <a href=”https://www.twitter.com/hashtag/plug2″ target=”_system”>#plug2</a> <a href=”https://www.twitter.com/hashtag/plug3″ target=”_system”>#plug3</a>

Just what we needed, eh? 🙂

Reference

Here’s a documentation of the available attributes, so you can go ahead and use it:

Attr. name Type Default value Note
nl boolean true convert new-lines
url boolean true convert URLs
email boolean true convert e-mail-addresses
phone boolean false convert phone-numbers, might be buggy
target string _blank define target for all links
hashTagURLPrefix string null convert hash-tags and define the URL-prefix
mentionURLPrefix string null convert mentions and define the URL-prefix
mentionAtShown boolean true show / hide the @-sign for mentions

 

0

Web-app CoWorker giver mulighed for alle folk til at benytte sig af kontorlokaler.
Man booker på forhånd et ønsket lokale til en ønsket varighed. For at få adgang til det lokale i det tidsrum, lukker appen døren op for en.

Det er en meget omfattende app, som håndterer bl.a:

  • brugerregistrering
  • registrering kompetencer
  • online betaling
  • booking
  • booking invitationer
  • booking reminders
  • låse kommunikation

CoWorker

CoWorker flow

Denne web-app er en sammensatning af Django, Bootstrap og Javascript.

0

Morsø Tømmer- og snedkerforretning har godt fat de lidt ældre kunder. Deres ønske var at få lige så godt fat i de yngre, ved at udarbejde en strategi for hjemmesiden og sociale medier, som vil appelere til det yngre publikum. I samarbejde med Jeanette Lund Kommunikation har sejKo lavet et moderne (men ikke overhipt) website, med et modernt look og tilgængelighed hvor deres referencer skal springe i øjet.

MTS Mors

Hjemmesiden på mobil:

MTS Mors mobile

Se mtsmors.dk

0

Dette efterår har sejKo fået lavet en række udvidelser til Mega Journal.

Mega Journal er et udbredt journal system, som sejKo har special udviklet til den selvejet institution Kvadderkjær, for ti år siden 🙂
Systemet bliver en gang i mellem udvidet med nye features og forbedringer, som opstår efter aktuelle behov.

Kvadderkjær - Mega Journal

0

Sidste uge havde sejKo Jonathan Klainberger i praktik.
Det er hårdt men hyggeligt at være praktikant her; først skulle den 15 årige Jonathan følge sejKos programmering lynkursus (med Kaj & Andrea eksempler!) så vises der basics af HTML & CSS (og sikke en funky sider der kom ud af det!), så afsluttes fredagen med et opbygning at et simpelt skyde-spil i Javascript – og en Kaj kage selvfølgelig 🙂
Tak for besøget Jonathan!