This is the second 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 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.
“The rest” can be assigned to a variable, using the rest-operator. Look at these rest-arguments:
Note that the rest operator must be a function’s last parameter!
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:
The last example is called destructuring. In ES6 you can destructure ‘iterables’ (Array, Map, Set) and objects.
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.
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:
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.
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 🙂
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:
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:
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:
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:
The short notation variations and implicit returns makes lambda kinda work a breeze:
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:
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:
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:
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:
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.
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.
If you want to retrieve public data from Facebook (typically a Page) you nowadays will have to use Facebook Graph API and thus provide an access-token. In the old days you could use some of the available feeds (following the RSS-principles) but that was back then.
I’ve seen some strange hacks around, but it’s quite simple to pull public data with a non-expiring access-token. (Impatient ones go here!)
The idea behind access-tokens is that the system you’re communicating with ‘knows something about somebody’; is that somebody a valid logged-in user, what is that user allowed to do, etc. For every request your application makes, on behalf of that user, you pass that access-token to the system.
Access tokens typically expire; to reduce the chance of getting in the wrong hands (Facebook offers appsecret_proof to prevent hijacking). When the user uses the application access-tokens get renewed in the background, when the user doesn’t use the application before the access-token expires, a new login / authorization action will provide a new one.
Facebook Graph API knows short- and long-term access-tokens, where the short-term tokens are used by the application’s client and the long-termed by the application’s server (using an app-secret).
The access-tokens mentioned above are “user access-tokens”. If you just want to pull out some public data, having users logging in and expiring access tokens is probably not what you want. But you can also in make requests to Facebook’s API on behalf of an a Facebook App, in stead of a user, working with an “app access-token”.
When you create an app at Facebook for developers, you have an app-id and an app-secret. In stead of requesting “oauth” for an app access-token, you can construct one yourself by combining your app-id and app-secret, when requesting from a server (not client!!), like this:
Note: using “appsecret_proof” doesn’t make much sense here
I needed to display posts from a Facebook Page via Javascript (with Ember.js to be exact). No further Facebook interaction was needed, so user access tokens were not what I was waiting for, I needed an access token that does not expire, and that I’m in control of, not some user. So I opted for using the “app_id|app_secret”-solution with an app access-token, mentioned above. That I had set up as a proxy on my webserver. The flow now is: Client -> Webserver -> FB API -> Webserver -> Client.
Here’s the method I used at the webserver (in PHP) to make calls to Facebook Graph API
For the ones interested in how you easily can work with the requested Facebook data in Ember, stay tuned and I’ll provide a snippet for your serializer.
Of course we’re using Ember Data to handle all this. First of all, model your data by adding a new model. You will at least have to define those attributes corresponding the fields-parameter from your API request.
For example ‘message’,’created_time’. Now setup your adapter, connecting to your ‘proxied webservice’.
When the data comes back to your client and back to Ember, Facebook has a slight different JSON-format than Ember expects, so we have to serialize it a little.
And what Ember expects depends whether you’re using the ‘old’ or ‘new’ adapter for handling JSON.
The previous de facto standard was the Ember Data RESTAdapter, the current de facto standard is the Ember Data v2 JSONAPIAdapter. What do they expect:
Ember Data RESTSerializer (using the extractArray method)
Ember Data JSONAPISerializer (using the normalizeArrayResponse method)
This is the model I’m using
Model
The fields comment_count, like_count and share_count do not exist in the response from Facebook, they’re nested in ‘comments’, ‘likes’ and ‘shares’ objects. With the serializer’s normalize method you can make the response-data fit into your model.
Another thing I did here is adjusting the date-format given by Facebook, as Moment.js by default will fail with that input on Safari and IE, when there’s no colon in the time-zone.
Add this method to your serializer (either RESTSerializer or JSONAPISerializer) to get the model straight:
Denne artikel skriver jeg i anledning af blog-posten på nedenstående link:
https://www.wordfence.com/blog/2016/02/wordpress-password-security/
Jeg anbefaler at du læser ovenstående blog-post, men her er en kort opsummering:
Wordfence sikkerhedskonsulenterne har i en måling på 16 timer registreret over 6 millioner password angreb på over 70 tusinde forskellige websites der bruger deres software.
Disse angreb er hovedsageligt såkaldte ‘brute force’ angreb, som betyder at en ‘robot’ forsøger forskellige login kombinationer indtil der er ‘bingo’.
De viser en liste over top lande hvor angrebene er blevet udført fra, og Ukraine får her en velfortjent førsteplads.
‘Brute force attacks’ er den mest enkele form for angreb og er derfor også en af de mest forekommende.
Ved en kombination af hosting hos Away IT og et af sejKos sikkerhedspakker står man stærkt:
Fordi kodeord ofte er det svageste led i en hjemmesides sikkerhed, kan man, sidst men ikke mindst, gøre hele websitet fri for kodeord via en såkaldt ‘two-factor authentication’. Læs mere herom i denne artikel “Bare glem dine kodeord”.
Models, as the name presumes, do ‘model’ data; they sort of outline data, from which content can be created. With that in mind, it’s not unlikely you want to validate created content every once and a while. Notify that given content is or isn’t the way the model intended the data to be.
The approach in this article is adding validation functionality (call it tools) to a model, before modelling. When a developer ‘models a model’ he can tell what each field should or shouldn’t accept for given content.
It’s a REALLY SIMPLE approach, there are other more complex, perhaps more ’emberish’, solutions out there. But this has you up and running quickly, and has useful functionality for templates and can thus be used in combination with input elements, especially when you have your input bound with model-fields, such as {{ input type=”text” value=model.employeeName }}.
Download the file here
I’m assuming you’re using Ember-CLI.
You can follow the extended instruction in the file-comment, but I’ll briefly show you what it’s about, so you get an idea whether this suits your project or not:
Put the file in you model directory (or somewhere more appropriate), and import it to your desired model, say a Person model:
/your-app/models/person.js
Elsewhere in your code you could be doing something like this:
Those model-errors are very useful in your templates, where you could either use all error-messages, model.errors.messages or field-specific error-messages, model.errors.age.errors (=array where each error-item has a message).
More info regarding model-errors at: http://emberjs.com/api/data/classes/DS.Errors.html.
Read how and when to set error-messages in the file’s comment.
Good luck and I hope you can use it some day!
Så er det fra i dag af, at Google søgemaskines indeksering afhænger af mobilvenlighed (Læs: http://googlewebmastercentral.blogspot.dk/…/finding-more-mo…)
Betragter Google din hjemmeside som mobilvenlig, får den en højere indeksering.
Test her om din hjemmeside er ‘Google Mobile Friendly’:
https://www.google.com/webmasters/tools/mobile-friendly/
Kontakt sejKo hvis du vil høre nærmere om din hjemmesidens mobilvenlighed.