Quiz dev privacy policy

Privacy Policy

Last updated: (8/14/2017)

Evolution Sys (“us”, “we”, or “our”) operates quiz dev (the “Mobile App”). This page informs you of our policies regarding the collection, use and disclosure of Personal Information we receive from users of the App.

We use your Personal Information only for providing and improving the App. By using the App, you agree to the collection and use of information in accordance with this policy.

Information Collection And Use

While using our App, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you. Personally identifiable information may include, but is not limited to your name (“Personal Information”).

Log Data

Like many app operators, we collect information that your browser sends whenever you visit our app (“Log Data”).

This Log Data may include information such as the pages/sections of our App that you visit, the time and date of your visit, the time spent on those pages and other statistics.

In addition, we may use third party services such as Google Analytics that collect, monitor and analyze this …

Communications

We may use your Personal Information to contact you with newsletters, marketing or promotional materials and other information…

Security

The security of your Personal Information is important to us, but remember that no method of transmission over the Internet, or method of electronic storage, is 100% secure. While we strive to use commercially acceptable means to protect your Personal Information, we cannot guarantee its absolute security.

Changes To This Privacy Policy

This Privacy Policy is effective as of (8/14/2017) and will remain in effect except with respect to any changes in its provisions in the future, which will be in effect immediately after being posted on this page.

We reserve the right to update or change our Privacy Policy at any time and you should check this Privacy Policy periodically. Your continued use of the Service after we post any modifications to the Privacy Policy on this page will constitute your acknowledgment of the modifications and your consent to abide and be bound by the modified Privacy Policy.

If we make any material changes to this Privacy Policy, we will notify you either through the email address you have provided us, or by placing a prominent notice on our website.

Contact Us

If you have any questions about this Privacy Policy, please contact us.

Quick Introduction to VueJS

vuejs

What is Vuejs?

What makes VueJs special is the fact that was designed to be incrementally adoptable, the core is dedicated to the view layer only but you can combine it with other libraries in order to create great single pages apps. Is very versatile and flexible yet lightweight, there is also components that allows you to handle routes and AJAX requests, hence is able to provide high quality results from a little gadget to a more complex SPA.

Why chose Vue.js?

  • The documentation is so good that it is the only tutorial you will need to understand and be able to dominate Vue.js efficiently.
  • The Vue.js community is growing.
  • Solutions through libraries and plugins well supported.
  • The way Vue.js do the things allows you to produce great code, efficient as well as readable.

Comparison with other frameworks

Vue.js vs React

Similarities:

  • Uses a Virtual DOM
  • Reactive and composable view components
  • Focused on the core library, so global state management and routing are delegated to third libraries

Differences:

  • Vue.js offers better performance than React, As you can see here.
  • In React all the UI components are represented rendering functions using JSX. In the other hand Vue.js provides render functions, provides support for JSX and also as default offers declarative templates (very readable by the way).
  • The ecosystem around custom renders makes React a winner in this aspect.
  • In matters of CLI Vuejs got leverage because of the limitations of React in this area, related with the lack of configurations.
  • Before to start working with React you should be familiar with JSX and ECMAScript 6, because most of the examples out there uses It, in the other hand Vuejs is more simple, to get it running you just need a single script on your page.

Vue.js vs Angular 1
Similarities:

  • Vue.js in an early stage of development inspire in the Angular syntax (e.g. v-if vs ng-if).

Differences:

  • Vue.js is way much simpler than Angular 1. A newbie is able to write functional code in a day with Vue.js, with angular, the learning curve is more higher.
  • Angular 1 ‘forces’ you to build the app under a specific and non-so flexible structure. Vue.js in the other hand is more flexible and modular.
  • Vue.js enforces a one-way data flow between components while Angular 1 uses two-way binding between scopes.
  • Vue.js offers better performance than Angular 1 because Angular one uses dirty checking with a cycle digests this can affect the performance.

Vue.js vs Angular 2:

Similarities:

  • Performance is equal because both are very fast.
  • Both are well suited for Enterprise environments.

Differences:

  • Vue.js is more flexible than Angular 2 in terms of the app architecture. Angular has a well defined architecture, Vue.js is more simple.
  • In terms of learning curve, Vue.js is extremely low while Angular 2 is too steeper.

To see more comparison of VueJs and other frameworks, you can go here:
https://vuejs.org/v2/guide/comparison.html

Simple app example with Vue.js.

Let’s create an simple object in javascript

 
var example = {
message: ‘Hi Vue’
}

This is going to be the template

 
<div id="container">
{{message}}
</div>

Vue in action, binding the template with the object:

 
new Vue({
el: '#container',
data: example
})

Here is a working example

 
Let’s see an example making use of a Vue.js directive: v-for:

This is the html template:

 
<html>
 <head>
<script src="./vue/dist/vue.js"></script>
 </head>
<body>
 <div id="app-example">
 <p v-for="human in people">                        
 {{ human.name }}
 </p>
 </div>
</body>
<script src="./app/myapp.js"></script>
</html>

Binding the template with the data

 
var app = new Vue({
  el: '#app-example',
  data: {
    people: [
     {name: 'albert'}, 
     {name: 'john'}, 
     {name: 'justin'}
     ]
  }
});

Here is a working example:
 

More examples can be found here: https://vuejs.org/v2/guide/, the introduction guide to Vue.js is one of the best tutorials you’ll find.

Let’s see another example, this time we are going to create a custom filter to reverse the text:
 

Here is an example where I use more concepts like, filters, methods, computed, the code is commented but if you don’t understand the concepts and how it works you can visit the Vue official documentation, or see this video from Egghead:
https://egghead.io/courses/develop-web-apps-with-vue-js

Introduction to Reactive programming RxJs

 
Reactive programming is a general concept that you can find in any language, it is often associated with event driven UI, asynchronous programming with observable, where you can subscribe to events. Reactive Extensions (abbreviated Rx*) provides libraries for a wide variety of programming languages, including JavaScript (RxJS). RxJS it precisely that, an extension/library for JavaScript.
 
Reactive programming RxJs

  • What is Reactive programming RxJS?
  • But wait, what is an observable?
  • Anything can be a stream
  • Where can I use RxJs?
  • Try yourself
  • RxJS Observables vs Promises
  • RxJS integration with AngularJS.
  • Differences between RxJs and Knockout
  • Conclutions

What is Reactive programming RxJS?

Reactive programming RxJS or Reactive Extensions for JavaScript is a reactive streams library that can be used in the client-side in the browser or server-side with Node.js. to work with asynchronous data streams. From the perspective of JavaScript let’s analyze the last three words of the previous sentence: asynchronous – data – streams.
Asynchronous – Is the fact of calling a function and then register a callback when results are available, this way we are notified about the returning of that function and been able to continue with execution avoiding non responsive behavior in our page.
Data – Raw information represented by any data type: Number, String, Objects.
Stream – Data made available over time meaning that you don’t need the presence of all the information to start using it for example mouse clicks, user inputs, database queries or just the call to an API.

But wait, what is an observable?

Observable is a JavaScript implementation of the observer pattern (also known as ‘publish/subscribe’).
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems.

Anything can be a stream.

Taken from this great article of Gerard Sans.
Asynchronous data streams are a pretty old concept, it exists since Unix and take different names and behavior depending on the environment for example in Node.js they are called ‘streams’, ‘pipes’ on Unix and ‘async pipes’ on Angular 2.
reactive programming: programming is called reactive when you are working with Asynchronous data streams.
Using RxJS asynchronous data streams can be represented through Observables and manipulate those streams with different operators as if they were simple collections of data. Next section has some examples.

Where can I use RxJs?

Creating and subscribing to simple Observable sequences

First include rx.js file in your code, you can use a CDN https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js:

<script src="rx.js"></script>

If using Node.js:

var Rx = require('rx');

Lets create a very simple example so you get the idea of how it works.
For this we are going to create a textarea (the stream acting as event generator) we are going to show to the user what we are writing in the textarea plus a fixed text (this is the reaction). This is going to looks like a data-binding between the textarea and the label.

<textarea></textarea>
  <p>
    <strong>Text:</strong>
    <code id="text"></code>
  </p>

 
const text = document.getElementById('text');
const area = document.querySelector('textarea')

const content$ = Rx.Observable
  .fromEvent(area, 'keyup') // each `keyup` throws an event on the stream
  // shows the content of the text area concatenated with the string ‘Fixed text’
  .map(e => e.target.value.trim() + ' Fixed text');

The suffix $ on the variable named ‘content’ it used to indicate that the variable is a data stream.
So, the data stream ‘content$’ will launch a new event each time the user inputs a new letter. The correct way to react to this constant stream of data is through the function “subscribe()” like this:

 
content$
  .subscribe(text => {
    console.log(`The textarea content is: ${text}`)
    text.innerText = text;//print the text.
  });

Now that we got the idea lets implement something more practical like a “word counter”, in order to obtain the amount of words, we need to update the stream and update the user interface to show how many words are written. To do this we need the function ‘map()’ which is one of the many operators provided by RxJS (a full list of RxJS operators can be found here):

 
content$
  .map(content => content.trim().split(' '))// make the string into an array of words
  .map(wordList => wordList.length)// count the array elements
  .subscribe(totalWords => {
     text.innerText = totalWords
  })

Each step is transformed into stream and return a modified object to the next step. Finally we are going to use the function ‘subscribe()’ where we indicate what is going to be the reaction, in this case, the reaction is to update the user interface to show the amount of counted words.

Try yourself (full code):

I recommend you to read this tutorial for better understanding of the subject:

The introduction to Reactive Programming RxJs you’ve been missing

What operator to use

 

RxJS Observables vs Promises

Promises is a concept from javascript async programming. Basically the Promises give an abstracted help to work with asynchronous matter’s inside the apps. The promise is the eventual result of an asynchronous data stream task. For better understanding read this and analyze the example code text taken from here:

“The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. You can create them very easily where the constructor has two functions, resolve and reject which resolves the value or rejects it for a given reason “

  • Observables are cancellable. Observable also has the advantage over Promise to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn’t needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don’t need the notification or the result it provides anymore.
  • The main difference here is that Promises in order to be able of retry the call, the caller must have access to the original function that return the Promise. In the other hand Observables are cancellable and the API provides operators to retrieve them (‘retry’ function).
  • A Promise handles a single event when an async operation completes or fails.
    Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far.

RxJS integration with AngularJS.

You may write a custom helper function to integrate this two but as you also may expect this task is already done. A library called rx.angular.js is in charge of this interoperability. Let’s analyze an example of using DOM-events:
To be able of use DOM-events we are going to use Rx.DOM, an HTML DOM bindings for RxJS provided by rx.angular.js. The next code is a feature to detect the time of inactivity of the user.

 
mergedStreams = rx.Observable.merge(  // mergin all the events coming from the user
rx.DOM.keydown(document), // keystrokes
rx.DOM.click(document), // mouse click
rx.DOM.mousemove(document), //mouse move
rx.DOM.scroll(document), //scroll
rx.DOM.touchstart(document) // taps
);

var idleStream = mergedStreams
.bufferWithTime(5000) //operator bufferWithTimes to catch all the event in buffer
.filter(function(arr){ //to check when the sequence is empty to notice that user is gone.
return arr.length===0;
})
.subscribe();

For more examples of how to integrate AngularJs with RXJs visit here:

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/howdoi/angular.md

Differences between RxJs and Knockout

The main main difference is:
 
Reactive programming RxJs allows composing operations against asynchronous streams , like http web requests or events, and includes advanced scenarios like combining streams for example when both event A and event B occur, execute X code, but stop it if B occur again.
 
KnockoutJs is an MVVM (not MVC) framework, with it you can manage the state of yourUI with a model that maps it’s functionality. This allows your to separate the logic from the view and the UI state.

 

Steve Sanderson, creator of Knockout, explained the difference on his blog:

I’m very familiar with Rx for JavaScript, having recently used it heavily on a big project, and in fact aspects of the design of Knockout are made with my Rx experiences in mind.

The key difference between Knockout’s implementation of the observer pattern and Rx’s is that Knockout automatically infers the associations and dependencies between observable from regular procedural code without you having to specify them up front though a special functional API. I wanted Knockout to use regular procedural/imperative-style code as it’s more familiar and approachable for most developers.

Another difference is that Rx is optimized for composing streams of events without state. At first I was enthusiastic about this and its functional purity, but after some time it felt increasingly like I was jumping through awkward hoops and had to invent extra ways to simulate state to manage UI commands efficiently. That’s why, in Knockout, all observables can be treated as stateful – for example you can always read their latest value (which is cached, by the way – it doesn’t recompute until the underlying data changes).

Rx goes further than Knockout into advanced ways of composing event streams, whereas Knockout goes further than Rx into UI development, letting you bind its observable to HTML DOM elements and templates and manipulate them any way you want. Rx is great at what it does but turned out not be be exactly how I wanted to build rich UIs – hence the design of Knockout.

Conclutions

I hope this article can be used as a starting point to dive into reactive programming for javascript RxJs, I encourage you to keep researching and learning about it since the intend of this post is to introduce the concept and make a comparison with other libraries like KnockoutJs, etc.

ASP.NET Core 1.0

In this opportunity I will be writing about one of the most used (and newest) and functional server-side web application framework: ASP.NET Core. Before entering into the ecosystem of this tool allow me to give you some feedback that may be needed in order to have a better understanding of topics related with versions, features and releases (this one is quite new).

Asp.net core

What is ASP.NET Core 1.0?

ASP.NET Core 1.0 is, in short terms, the evolution of ASP.NET 4.6. If you are thinking that it is just a superior version of ASP.NET 4.6 take away that myth of your head because ASP.NET Core 1.0 is an entire new based-cloud applications framework written from scratch, with a new focus different from its predecessor.
Two of the most appreciated characteristics of this new framework are:
First it is open source (supported by Microsoft) meaning that you can find and download the code on GitHub , also contribute to the development of it, and second, it is cross-platform, so you can run it either in Windows, Linux or Mac OS.

Advantages and Disadvantages. Looking back to ASP.NET 5.

Good:

– Open source: as I mentioned before, this is a huge advantage and everybody loves it.
– Cross-platform: this is an obvious point, run it everywhere!.
– Modular design: the main stuff here is NuGet packages. Developers can use NuGet Package Manager to install libraries to extend the features of apps so now is easier to maintain the code due to the benefits of package-based software.
– MVC and WEB.API are together in one: Back in ASP.NET, MVC and WEB.API were based on different versions of the framework and because of this some differences related to namespace and classes were present and tend to confuse sometimes. Now arrives MVC 6, a unique collection of objects with a unique namespace (Microsoft.AspNet.Mvc), this standard simplifies the development process.
– Dependency injection: Before this was available as an ad-on but now it is built-in the framework, but still third party’s solutions like Autofac should be functional.
– Productivity: The keyword here is Kestrel, a lightweight web server incorporated by Microsoft as an alternative to developer’s who does not want to use heavy options to host development. With Kestrel you can run the site in OSX.
– Easier integration with client-side frameworks like AngularJS, KnockoutJS and Bootstrap.

Bad:

– Issues with documentation in certain way: When in May of 2016 the RC2 of ASP.NET Core 1.0 was released the documentation was ‘incompleted’ because a lot of topics were without text. Today this situation was patched but sometimes you can find some cases, take in count that ASP.NET Core 1.1 is out too. God bless StackOverflow! 😉
– Sometimes when you are searching for information maybe a little bit hard, because this framework had many names in the past, first vNext, next ASP.NET 5 and today ASP.NET Core, this is not helpful.
– Compatibles solutions between versions not always is the best. You can find a solution to a specific trouble but it may not work because maybe it was written to a previous version. Thanks to GitHub and open source this can be fixed eventually because there is always an alternative.

What about ASP.NET Core 1.1?

The .NET Core 1.0 was updated with some changes, you can see them all here in the release notes.

Some of them are:
– Improved middleware in all sense through the user interface.
– Improved deployment of ASP.NET core apps on Microsoft Azure, increased the cloud support.
– Now other hosting options are available, beside IIS.

Let’s see an example of code, in this case it going to be an URL Rewriting Middle ware: (this was taken from here, check it if you want to see more examples.)

“URL Rewriting allows mapping a public URL space, designed for consumption of your clients, to whatever representation the downstream components of your middleware pipeline require as well as redirecting clients to different URLs based on a pattern.”

 
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
namespace MyApplication {

public class Startup {

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{

var options = new RewriteOptions()
.AddRedirect("(.*)/$", "$1") // Redirect using a regular expression
.AddRewrite(@"app/(\d+)", "app?id=$1", skipRemainingRules: false) // Rewrite based on a Regular expression
.AddRedirectToHttps(302, 5001) // Redirect to a different port and use HTTPS
.AddIISUrlRewrite(env.ContentRootFileProvider, "UrlRewrite.xml") // Use IIS UrlRewriter rules to configure
.AddApacheModRewrite(env.ContentRootFileProvider, "Rewrite.txt"); // Use Apache mod_rewrite rules to configure
app.UseRewriter(options);
}

// More Code

}

}

From .Net Framework 4.6 to .Net Core 1.0 :

asp.net core chart

This images illustrates the main changes with its predecessor. I recommend you to read this post to understand some considerations before migrating from .NET 4.6 to .NET Core 1.0 as well as strategies and advices from the author to achieve it. In case you are not sure about what solution suits you, and need to pick, this post can give you a clear understanding.

Other resources to learn more about ASP.NET Core

Tutorials

Microsoft Virtual Academy – Introduction to ASP.NET Core

Building your first ASP.NET Core MVC application

Building Your First Web API with ASP.NET Core MVC and Visual Studio


 
 
 

JSX preprocessor – A syntax sugar for ReactJS

The JSX preprocessor

JSX preprocessor it is a step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

When you start typing code, driving yourself into the amazing world of web programming sometimes you may feel overwhelmed when you have to select a tool, a library or a framework as your initial learning point. Out there are too many tools, each one with different features aiming the same goal in their own way. Eventually you realize that HTML and CSS are not enough, you need JavaScript. And now for react you are able to use
JSX preprocessor.

JSX preprocessor

At some point, vanilla JavaScript became too heavy and hard in order to achieve certain task, the most efficient way is to make use of a library or a framework.
This time is the turn for ReactJS, it is a JavaScript library, and specifically one of its many features: JSX. Now, we will assume you already know something about ReactJs and the ecosystem around it. Otherwise you should start here first and then move on to this topic.

ReactJS feature:
Basically JSX is an inline markup that looks like XML/HTML and gets transformed to JavaScript (sometimes it can remind you a template language). It is possible to use ReactJS without JSX but JSX makes ReactJS code more elegant. A JSX expression starts with an XML/HTML-like open tag, and ends with the corresponding closing tag, it also supports the XML syntax so you can optionally leave the closing tag off. See the follow example:

 
const hw = <p>Hello, world!</p>;

This code is just JSX syntax example but you also can do things like embed JavaScript expressions in JSX by wrapping it in curly braces:

 

function hello(text) {
  return text.firstWord + ' ' + text.secondWord + '!';
}

const text = {
  firstWord: 'Hello',
  secondWord: 'World'
};

const element = (
  <p>
    This is a, {hello(text)}!     // embed JavaScript expression 
  </p>
);

Even specify attributes like follow:
You may use quotes to specify string literals as attributes:

 
const element = <div z-index="1"></div>;

You may also use curly braces to embed a JavaScript expression in an attribute:

 

var style = { backgroundImage: 'url(picture.png)', height: 10, width: 15 };
return <div style={style}></div>;

Now let’s analyze an example combined with ReactJS.

ReactJS applying JSX

 
var test = (  
  <div className='test-example'>//notice the parameter className instead of class
    <img 
      src='image.png'
      className='test-example'
    />
  </div>)

ReactDOM.render(test, document.getElementById('myapp'))

As you can see, it is like write HTML/XML code inside JavaScript but at the end it is just JavaScript. The special consideration is that JSX makes you name the attributes in a different way form the standard, in the example above, the ‘class’ for CSS must be named ‘className’ instead of the html standard attribute ‘class’.

Basically JSX produces React “elements” and according to the official documentation ‘JSX just provides syntactic sugar to React.createElement(…) function’, see below:

 

<MyButton color="green" shadowSize={10} >
  Go!
</MyButton>


 
compiles into:
React.createElement(
  MyButton,
  {color: 'green', shadowSize: 10},
  'Go!'
)

JSX preprocessor Pros:

Declarative syntax:
Provides a very easy way to import static HTML or migrate from JavaScript templates. Plus, its enforces good syntactical restrictions similar to XHTML that improves quality of codebase.
ReactJS Documentation priories JSX:
ReactJS documentation uses JSX everywhere so JSX is only going to become more powerful.
Very useful tools and resources:
Babel is a tool able to transpiles ES6, ES7(stage 1 flag), JSX altogether.

Integrations with other frameworks

JSX simple example with AngularJS:
You can integrate JSX preprocessor with Angularjs to write the templates in places that you use javascript, for example in the directives.
If you want to use JSX-style with AngularJS the way is through AngularJS directives. In order to achieve this goal, we have angular-jsx library to convert templates into strings that Angular can understand. Take a look to this example:

Input

 
angular.module("foo").directive("bar",
    function() {
        return {
             // it can be used in the template for the directives
            template: <div>This is a simple example.</div>
        };
    }
);

Output

 
angular.module("foo").directive("bar",
    function() {
        return {
            template: "<div>This is a simple example.</div>"
        };
    }
);

More information about it can be found here. If you want a deeper point of view about more technical aspects related to ReactJs and JSX maybe this article will do the trick for you.

Redux with React – First look

redux with react
This time I going to take the time to research and write about Redux in combination with React, one of the hottest libraries for front-end web development. It was created in 2015, influenced by Flux architecture and became popular very quickly because of it’s simplicity, excellent documentation and size (2 KB). Also is very easy to use redux with react. Let’s start with the basics:

What is Redux?

According to the official site Redux is defined as a predictable state container for JavaScript apps. Basically Redux maintains the state of an entire application in a single immutable state tree (object). This object can’t be changed directly. When something changes, a new object is created (using actions and reducers). The main goal of Redux is to facilitate the task of connect sources of different environments like for example APIs and sockets.

Redux with React.

Redux is kind of ‘created’ to work with React.js but also can be used with Angular.js, Backbone.js or just vanilla JS.

How to install it?

To install the stable release (through npm as package manager with a module builder like Webpack or Browserify to use modules of CommonJS):
npm i -S redux
Also you may want to install the connection to React and the developer tools.
npm i -S react-redux
npm i -D redux-devtools

Core concepts of Redux

1 – Actions.
The actions, summarized actions are events. The action task is to send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The only way to pass information to the store is through actions. The actions are POJO (Plain Old JavaScript Objects) with at least one property that indicates the action type and, if necessary, others properties indicating any other necessary data to do the action. Normally they use the format defined in FSA.

An action example:

 
{
    type: 'TODO_APP',
    payload: {
        text: 'How to learn Redux,
    },
}

Actions are created with action creators. They are just functions that return actions.

 
function myAction(someText) {

return {
	type: TODO_APP,
	payload: someText
}
}

To call an action anywhere in our app must be through dispatch method, like this:

 
// to send an action to the Store (The concept of Store will be seen ahead).
Store.dispatch (myAction(someText)); 

2 – Reducers.

While the actions describe that ‘something’ happen they don’t specify how our app reacts to that ‘something’. In Redux, reducers are functions (pure, I will explain what a pure function is later) that take the current state of the application and an action and then return a new state.
(prevState, action) => nextState
Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

 

function handleAuth(state, action) {
	return _.assign({}, state, {
		auth: action.payload
	});
}

Some things you should never do in a reducer:
Modify the arguments directly (the right way is to create a copy first.)
Do actions with secondary effects like API calls or change a route.

The name we put to the reducer is used as property of ‘store’ we created and is where will be saved the state returned from the reducer.

3 – Store
Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers.
The store has four main responsibilities:
Store the global state of the app.
Give access to the state through store.getState()
Allow the update of the state through store.dispatch()
Register listeners through store.subscribe(listener)
Take this as example:

 

import { createStore } from 'redux';

	let store = createStore(rootReducer);
	let authInfo = {username: 'alex', password: '123456'};
	store.dispatch(authUser(authInfo));

This image illustrates the work flow of Redux.

redux dataflow
Redux data flow (Image: Tanya Bachuk)

The three principles of Redux.

– Single data source: The app state stores in one objet tree inside a unique STORE.
– The state is read only: The only way of change the state is through ACTIONS.
– Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.

Where can Redux be used?

Contrary of what you may be thinking, the only use of Redux isn’t with React. It can be integrated with any other library/framework like for example Vue.js, Polymer, Ember, Backbone.js or Meteor, but Redux plus React, though, is still the most common combination.

Integrating Redux with React: Installing react-redux

The connection of Redux with React isn´t included directly inside Redux, in order to achieve this, we need to download react-redux:
npm i -S react react-dom react-redux redux

Encapsulating the app.

First we need to encapsulate our app with the component Provider that comes with react-redux. This component receives a unique parameter called store which one is the instance of the STORE we are using. See the follow example.

 
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import React from 'react';
import store from './store';
import App from './components/App';

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
);

This component Provider defines in the global context of React our instance of store.

Accessing the store.

Now is time to define what components are going to Access our Store, because not all of them will need to. In order to do that we need to connect our Redux components to Redux, this can be achieved with a decorator that came with react-redux called connect.

 
// Importing the decorator @connect of react-redux

import { connect } from 'react-redux';
import React from 'react';
import UserItem from './UserItem';

// Aplying the decorator @connect to our component.

@connect()
class UserList extends React.Component {
  render() {
    // Rendering the user list we receive from Store  .  
    return (
      <section>
        {
          this.props.users
            .map(user => <UserItem {...user} key={user.id} />)
        }
      </section>    
    );
  }
}
export default UserList;

This way our component UserList will have inside it props all the data of the Store. With this we can render our app using the data stored in the Redux Store.

Pure functions vs Impure functions:

Pure Functions
A function is considered pure if:
a) It always returns the same value when given the same arguments.
b) It does not modify anything (arguments, state, database, I/O, ..).

Examples of Pure Functions (in JavaScript):

 
function add(x, y) {
return x+y;
}
 
function getLength(array) {
return array.length;
}

Impure Functions

A function is considered impure if it is not pure, typically because:
a) it makes use of an external or random value. (It stops being entirely contained and predictable.)
b) It performs an external operation, in other words it causes side effects.

 
var x = 5;
function addToX(a) {
return a+x; / Use of an external variable
}

Example: A complete reducer with tests (can use a library for this like Expect.js).

You might be interested in:

First look to javascript unit test framework – ExpectJs

 

const counter = (state = 0, action) => {

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
      
    case 'DECREMENT':
      return state - 1;
      
    default:
      return state;
  }
}

expect(
  counter(0, {type: 'INCREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'INCREMENT'})
).toEqual(2);

expect(
  counter(2, {type: 'DECREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'DECREMENT'})
).toEqual(0);

expect(
  counter(1, {type: 'DECREMENT Else'})
).toEqual(1);


expect(
  counter(undefined, {})
).toEqual(0);

console.log('Tests passed!');

Why would I need to use Redux? (extracted from this article)

Predictability of outcome:
There is always one source of truth, the store, with no confusion about how to sync the current state with actions and other parts of the application.
Maintainability:
Having a predictable outcome and strict structure makes the code easier to maintain.
Organization:
Redux is stricter about how code should be organized, which makes code more consistent and easier for a team to work with.
Server rendering:
This is very useful, especially for the initial render, making for a better user experience or search engine optimization. Just pass the store created on the server to the client side.
Developer tools:
Developers can track everything going on in the app in real time, from actions to state changes.
Community and ecosystem:
This is a huge plus whenever you’re learning or using any library or framework. Having a community behind Redux makes it even more appealing to use.
Ease of testing:
The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is mostly functions that are just that: small, pure and isolated.
Pure functions:
return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one. These functions don’t rely on the state they’re called from, and they return only one and the same result for any provided argument. For this reason, they are very predictable.
Because pure functions don’t modify any values, they don’t have any impact on the scope or any observable side effects, and that means a developer can focus only on the values that the pure function returns.

CONCLUSION

Redux has a growing popularity and is even bigger every day. Companies like Uber and Twitter and projects like WordPress are using it successfully in production. Redux isn’t a perfect fit for everything but we recommend to check it out. If you are up to it you can deep your knowledge over here, a tutorial from the Redux creator and see this example contains source code of Todo List app using Redux with React.

How to copy to clipboard using JavaScript

It is amazing how modern browsers had evolved, and how powerful they became we got to a point where we don’t need flash anymore.
A time ago the only way to copy to browser’s clipboard was from a button in the app using Flash, but with modern browsers we can achieve copy to clipboard using javascript, without using any plugin. First, let’s set the ground of what the clipboard is…

copy to clipboard using JavaScript

The clipboard is basically a place for storing and retrieving a single piece of cloned data, by data means from a simple string to a whole directory. There can be more than one clipboard present, for example, the “operative system clipboard”, it would be less difficult if all the applications were able/created to use the operative system clipboard, but unfortunately this is not always the case. For example, virtual machines, unless you explicitly turn on a clipboard integration option.
Following the same behavior are the web apps. Web applications runs in a sandbox environment, it restricts access to file system and the system clipboard, for security reasons. This article expose why the system clipboard is a restricted resource.
Fortunately, there ways to bypass those restrictions and gain access to system clipboard using JavaScript. This is post is about show several ways to do it.

Copy to clipboard using JavaScript

Example 1 (vanilla JavaScript):

This solution is a simple one but has some drawback because you must add an <input> or <textarea> element with the text to be copied to the DOM. The command used ‘execCommand’ allows us to execute other commands like cut, copy or paste.

The input or textarea to receive text you want to copy:

 
<input name="exampleClipboard" placeholder="Insert the text you want to copy" value="Example text" tabindex="1" autocomplete="off" maxlength="240" style="width:200px" type="text">
<p>
  <button id="copy">
    Copy text
  </button>
</p>
<p>
Right click paste or Ctr + v after click Copytext button <br/>
<textarea></textarea>
</p>

The function to call:

 

<script>
function copyToClipboard() {
document.querySelector('input').select();
document.execCommand('copy');}
</script>

The button:

 
<button id="howToCopyClipboard" onclick="copyToClipboard()">Copy</button

*You can change the input label for a textarea if you want. Keep in mind that this solution forces you to keep a maybe non desire input or textarea element in your page.

 
Try yourself

Example 2 (vanilla JavaScript):

This is a more elaborated solution where we validate compatibility with browsers. For this solution lets create a function that copies a string to the clipboard, this function must be called from within an event handler such as click. More reference to this method can be found here you can see a practical example here.

 

function copyToClipboard(text) {

if (window.clipboardData && window.clipboardData.setData) {
 // IE specific code path to prevent textarea being shown while dialog is visible.

return clipboardData.setData("Text", text); 

} 

else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy"); // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

Example 3 (with a library): Clipboard js

It would be overwhelm to have to write validations for browser compatibility, etc, so Lets avoid reinvent the wheel and use a library that manages all this for you. ClipboardJs is very easy to use, here is an example:

 
<!-- Target -->

<input id="textToCopy" value="Any text you want to copy">

 

 

<!-- Trigger -->

<button class="btn" data-clipboard-target="#textToCopy">Copy to clipboard
</button>

Notice that

 data-clipboard-target 

do the job here. Let’s see another feature but this time is to cut instead of copy.
The only change needed is to add

 data-clipboard-action="cut"> 

like this:

  
<textarea id="textToCopy">Another feature … </textarea>
  
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#textToCopy">
    Cut to clipboard
</button>

More reference about this useful library can be found here.

Try yourself

At the end there isn’t universal solution to this task, out there are a lot of solutions in many different ways with just JavaScript (or JavaScript libraries without involving Flash), feel free to use the most suited for you.

First look to javascript unit test framework – ExpectJs

Today I going to write about javascript unit test frameworks, to be more specific, about Expectjs.
Sometimes web developers ignores the action of testing their code, automated, just because it works in
some random manual attempts. Just a reduced number of developers really like the activity of write unit test because of the security and the mind peace it brings to any development process.
This time let’s take a look at ExpectJS, a minimalistic BDD assertion toolkit based on should.js that
provides very useful features to developers in order to test their codes through unit test. But how it
works exactly? In this post I’d like to expose the main features and APIs of this amassing library.
 
javascript unit test framework

Two definitions before go to the main topic: Assertions + Unit Testing with ExpectJs

Basically an assertion is a statement where a Boolean-valued function is expected to be true at that
point in the code. If the assertion evaluates to false in some point of the execution, it will throw an
assertion exception. For example:

 
function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}
 

In the other hand, a unit test checks blocks of code to ensure that they all run as expected. Simple JavaScript unit test will take a function, monitor output and return its behavior, and assertions are used in the process. Sometimes this task is not so easy with vanilla JavaScript.

Other javascript unit test frameworks

There are other options. Out there are plenty of javascript unit test frameworks like QUnit, Sinon, Mocha or Jasmin, all of them are able to integrate assertions libraries like ExpectJS.

Let’s get starting with ExpectJS

How to install it.
 
Node
Install it with NPM or add it to your package.json:
$npm install expect.js
Then you can use the following code:

var expect = require('expect.js');

Browser

<!-- download the file to your local -->
<script src="expect.js"></script>

<!-- from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.2.0/expect.js">
</script>

 

Main features

– Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
– Compatible with all test frameworks.
– Node.JS ready (require(‘expect.js’)).
– Standalone. Single global with no prototype extensions or shims.

Our first test

Let’s say we want to test the following add function:

function add(a, b) {
return a – b; 
};

expect(add).to.be.a('function');  // this assertion passes
expect(add(1, 3)).to.equal(4);  // this assertion fail
expect(add(5, 2)).to.be.lessThan(8); // this assertion passes

Now, notice that if we execute this code, and we check the console of the browser you’ll see an error for the assertion that failed (the second one).

 
Try it yourself

The previous approache is not too intuitive, so lets wrap it up with a framework that offers a more visual result, lets use MochaJs:

Comparing with other assertion test frameworks

Differences with should.js
– No need for static shouldjs methods like should.strictEqual(). For example, expect(obj).to.be(undefined) works well. More intuitive now!
– Some API simplifications/changes.
– API changes related to browser compatibility.

Let’s see how intuitive the ExpectJS API’s can be.

Example 1: a/an: asserts typeof with support for array type and instanceof (used with mocha testing framework)

describe("Example 1", function() {

 var n;
 var cars;

it("number check", function() {
    n = 'good';
    expect(n).to.be.a('number');
  });


  it("array and object check", function() {
    cars =['Mercedes', 'Toyota', '4x4'];
  
   expect(cars).to.be.an('array'); // it works
   expect(cars).to.be.an('object'); // it Works too since it supports typeof
  });
});

Example 2: match: asserts String regular expression match. We can use useful regular expressions like this:

describe("Regular expressions check", function() {
 var version;
it("version check", function() {
    n = '4.8.2';
    expect(version).to.match(/[0-8]+\.[0-8]+\.[0-8]+/);
  });
});

Try it yourself

Other resources the API provides:

ok: asserts that the value is truthy or not.

expect(1).to.be.ok();

eql: asserts loose equality that works with objects.

expect({ a: 'b' }).to.eql({ a: 'b' });

contain: asserts indexOf for an array or string.

expect([1, 2]).to.contain(1);

length: asserts array .length.

expect([]).to.have.length(0);

empty: asserts that an array is empty or not.

expect([]).to.be.empty();

property: asserts presence of an own property (and value optionally).

expect(window).to.have.property('expect')

key/keys: asserts the presence of a key. Supports the only modifier.

expect({ a: 'b' }).to.have.key('a');

throw/throwException/throwError: asserts that the Function throws or not when called.

expect(fn).to.throw(); // synonym of throwException.

withArgs: creates anonymous function to call fn with arguments.

expect(fn).withArgs(invalid, arg).to.throwException();

within: asserts a number within a range.

expect(1).to.be.within(0, 100);

greaterThan/above: asserts.

expect(3).to.be.above(0);

lessThan/below: asserts.

expect(0).to.be.below(3);

fail: explicitly forces failure. (This is very helpful sometimes).

expect().fail()

How to use it with spies.

A way to verify the function behavior in unit test is through the use of spies. A spy allows you to monitor a function exposing options to track invocation counts, arguments and return values. The main principle here is that it replaces a particular function where you want to control its behavior in a test, and record how that function is used during the execution of that test (similar to how actors are replaced with stunt doubles for dangerous action scenes in Hollywood movies).

Let’s see how it works: (Other examples can be found here)

spyOn(foo, 'bar');  // Here the spyOn method takes an object and a method to be spied upon.
foo.bar(1);         // Call the function
 
expect(foo.bar).toHaveBeenCalled(); // Run assertions with ExpectJS.
expect(foo.bar).toHaveBeenCalledWith(1);

Final considerations.

ExpectJS is a very useful assertion library and combined with other javascript unit test frameworks can be very visual and can save a lot of time while provide security to your code. Other libraries similar are Chai, should.js, and better-assert. One of the advantages is that it is Standalone and can be integrated with any javascript unit test frameworks.

References:

https://github.com/Automattic/expect.js/blob/master/README.md
https://abdulapopoola.com/2016/04/11/how-function-spies-work-in-javascript/
https://designmodo.com/test-javascript-unit/

TinyMCE Validating length AngularJs

 
 

I’m creating this “how to…” tutorial based on my experience working with TinyMCE Validating length with Angularjs, and the answers I found in the internet community Stack overflow and github.

What is TinyMce:

It is an opensource WYSIWYG (What You See Is What You Get) HTML editor designed to simplify website content creation. In other words it is a rich text web editor. This is the official website https://www.tinymce.com/

TinyMCE Validating length

TinyMCE Validating length using AngularJs

For the first example I used TinyMCE v4.3.3 with angular-ui-tinymce v0.0.12 plugin and AngularJS v1.4.6.

In the AngularJs controller we have to set the config options, and in the view we use a textarea with the parameter ui-tinymce=”tinymceOptions”


angular.module('myApp', ['ui.tinymce'])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 

<textarea ui-tinymce="tinymceOptions" ng-maxlength="100" 
name="editor" ng-model="vm.editor">
</textarea>
<span ng-show="form.editor.$error.maxlength" class="error">
    100 character limit reached!
</span>

 
 
The code above will not work as it is, because of a known bug https://github.com/angular-ui/ui-tinymce/issues/145

Work around

Took from StackOverflow
One work around can be to disable SCE mode with this code .config([‘$sceProvider’, function($sceProvider) {
$sceProvider.enabled(false);
}])
but…

Beware of security vulnerabilities!

Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. With SCE disabled, an AngularJS application allows to render arbitrary HTML into the div, and rendering user controlled input creates security vulnerabilities.

 
 

angular.module('myApp', ['ui.tinymce'])
.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 
Here is the JsFiddle https://jsfiddle.net/naXa/zsnLupvd/

Another work arround

This is a directive written by @andresmatasuares for TinyMCE Validating length with AngularJs.

app.directive('plainTextMaxLength', function($filter) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        var maxLength, validPlainTextLength;
        validPlainTextLength = function(v) {
          if (!v) {
            return true;
          }
          return stripHtmlTags(v).length <= maxLength;
        };
        maxLength = void 0;
        scope.$watch(attributes.plainTextMaxLength, function(newValue, oldValue) {
          if (maxLength !== newValue) {
            maxLength = newValue;
            return ngModel.$validate();
          }
        });
        return ngModel.$validators['plainTextMaxLength'] = function(modelValue, viewValue) {
          if (viewValue.$$unwrapTrustedValue) {
            return validPlainTextLength(viewValue.$$unwrapTrustedValue());
          } else {
            return validPlainTextLength(viewValue);
          }
        };
        
      }
    };
  });

 
Here you can find the plunker code http://plnkr.co/edit/oAZcHZAmCXYOTckJCPcs?p=preview

How to use filters within controllers in AngularJs (mini-challenge 12)

filters within controllers

Filters within controllers (mini-challenges 12)

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

How would you use filters within controllers like “filter” in JavaScript? And how to create a custom filter?
For example in the html you can use filter’s filter to do a search in a list of elements:

 <tr ng-repeat="friend in friends | filter:searchText">

<table id="searchTextResults">
<tr>
<th>Name</th>
<th>Phone</th>
</tr>

<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>

 
 

Solution:

In AngularJs you can inject the $filter service within the controller, and use it with the following syntax for “filter”:

$filter('filter')(array, expression, comparator, anyPropertyKey)

 

function myController($scope, $filter)
{
   $scope.result = $filter('filter')($scope.arrayOfObjects, $scope.searchCriteria);
}

You can also use other AngularJs filters Build-in like:

 $scope.formatedDate = $filter('date')($scope.date, "yyyy-MM-dd");
 $scope.result = $filter('lowercase')($scope.name);

You can find here a list of build-in AngularJs filters:
https://docs.angularjs.org/api/ng/filter

 
 
Filter Example with pipe in the HTML:

 
 
Filter example within the controller using Javascript:

 
 

How to create custom filters in AngularJs

AngulrJs have a build-in method to register custom filters, using the same approach you can use when you register a controller, a service and factories. See following example:

var myApp = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(input, option1, option2) {
    var output;
    // Logic to make your filter works.
    return output;
  }
});

 
for more reference about how to create a custom filter you can refer to https://scotch.io/tutorials/building-custom-angularjs-filters