DailyJS

DailyJS

The JavaScript blog.


Tagangularjs
Featured

decorator mysql ES7 angularjs

DecorateThis, jsRequest, ODataAngularResources

Posted on .

DecorateThis

DecorateThis (GitHub: mako-taco/DecorateThis, License: Apache 2.0, npm: decorate-this) by Jake Scott is the first library to my knowledge that takes advantage of ES7 decorators. Decorators allow you to annotate classes and properties.

An example of a decorator is @readonly:

class Person {  
  @readonly
  name() { return `${this.first} ${this.last}` }
}

This is far less complex than the older Object.defineProperty syntax:

Object.defineProperty(Person.prototype, 'name', {  
  value: specifiedFunction,
  enumerable: false,
  configurable: true,
  writable: true
});

The DecorateThis module provides some very handy decorators for argument type checking, including:

  • Memoization: @memoized
  • Type validation: primitive types @param(Number), and a class T is checked with @param(T)
  • Duck type checks: @param({ hello: String, info: { age: Number, color: String } });

If these checks fail type errors are thrown, which means you'll need exception handlers for places where these checks should be caught and handled gracefully.

jsRequest

Bruno Panuto and Danilo Valente have been working on a JavaScript file loader called jsRequest (GitHub: danilo-valente/jsRequest, License: MIT) since back in 2013. It handles asynchronous loading, and the syntax supports loading multiple files with a chained API:

jsRequest  
  .load('myScript.js')
  .load('http://code.jquery.com/jquery-1.10.2.js')
  .load('file:///C:/myFile.js');

It supports extra options that allow success and failure callbacks to be supplied, and it also has a progress callback. If you need to order requests, then you can use the wait method.

jsRequest tracks the request history, so if you need to check what files have been loaded you can inspect the jsRequest.history object.

ODataAngularResources

I recently wrote about OData Server, and Raphael Atallah sent in ODataAngularResources (GitHub: devnixs/ODataAngularResources, License: MIT), a fork of Angular's $resource that allows making OData queries using a fluent API.

Once you've added the dependency, you can do cool stuff like this:

var User = $odataresource('/user/:userId', { userId:'@id' });  
var myUsers = User.odata()  
  .filter('Name', 'John')
  .query();

You can also use top, orderBy, and skip, and request single elements. The readme has full examples including details on how to create more complex queries with predicates.

Featured

tutorials testing angularjs error-handling

AngularJS Form Errors, Angular Integration Tests

Posted on .

AngularJS: API Error Code Handling in Forms

When you're writing forms with Angular, it's not always clear how to handle errors in a reusable way. For example, what format should the server use to send back structured error message to the client? How do you use these responses to annotate fields with errors?

Szymon Kosno sent in AngularJS: API Error Code Handling in Forms, a tutorial that shows how to use error handling without explicit error handling in view controllers. It makes suggestions for how to structure detailed JSON error responses, and how to support different types of errors: for example, global errors and errors for specific form fields.

The form's markup uses an api-validate directive for input elements that should be validated by the server and will show error annotations. This allows the underlying error handling code to determine that the field is API error aware, so errors can be displayed or hidden as required.

With the right directives and services, Szymon is able to remove custom error handling code, which really cleans up the associated controllers. This article is useful if you've ever been confused about how to handle server-side errors, which you should always do for security and sanity.

Angular Integration Tests

Torgeir Helgevold sent in Angular integration tests, which gives some background to integration tests and includes a detailed example towards the end of the article.

In the following example I will demonstrate how to test a series of nested components with shared state. My sample code includes a parent directive where a user can add an inputed number to a list by clicking a button. Nested within there are two directives, one for calculating the sum of all items, and a second directive for building a comma separated string from the items in the list.

The example uses Angular's controllerAs syntax to simulate isolated scopes and pass changes. If you've ever used something like Selenium for integration tests, then you might want to compare Torgeir's approach if you're looking for something more lightweight and focused.

Featured

libraries modules npm angularjs state-machine

ngPromiseStatus, fsm-event

Posted on .

ngPromiseStatus

ngPromiseStatus (GitHub: BarakChamo/ng-promise-status, License: MIT, npm: ng-promise-status) by Barak Chamo is a collection of promise-aware Angular directives that make it easy to bind UI elements to the outcome of promises. This could be a button that takes an unspecified amount of time to run, that will eventually display success or failure.

You can also bind the promise values to alerts, and the author has provided Bootstrap samples that use Bootstrap's ubiquitous .alert message boxes.

fsm-event

fsm by Dominic Tarr is a very useful module for making finite state machines. I've used it with some success on a few Node projects. However, when I'm writing Node I prefer to deal with streams and events, rather than the methods in fsm's API. Yoshua Wuyts sent in fsm-event (GitHub: hyoshuawuyts/fsm-event, License: MIT, npm: fsm-event), a wrapper that uses EventEmitter.

To use it, create a new instance of fsm with the states you need, and then call m(state) to enter a given state. The corresponding listener will fire.

Why? Most state machines have overly complicated interfaces for managing state. The fsm state machine is simple but doesn't manage state for you, so I wrote a wrapper around it that manages state in an event-driven way. The initial use case was to manage complex, stateful UI elements but it can be used anywhere.

This would have actually helped with my specific use of fsm, where I ended up using it heavily alongside EventEmitter objects.

Featured

libraries databases node modules angularjs

JOQULAR, angular-atomic-notify

Posted on .

JOQULAR

Simon Y. Blackwell sent in JOQULAR (GitHub: anywhichway/joqular, License: GPL3, npm: joqular), a query language that can be serialised safely as JSON. It has 30 built-in predicates and operators, and extensive date and time representations.

It manages indexes using a just-in-time in-memory database, which is faster than a linear search:

Because JOQULAR defers 75% of the indexing effort until the first query requiring the index, the up front cost of indexing is marginal. It also turns out that the just-in-time indexing has a negligible impact on the first query. What is avoided and passed onto the user as time savings is lots of thrashing during object inserts and updates.

The authors claim it's faster than IndexedDB and PouchDB for insert and search.

The library was created as part of commercial work by the company behind it (AnyWhichWay). The original work was capable of querying Google Cloud Datastore, Quickbase, Elastic Search, and some Amazon AWS services using the same expression language.

To make queries, you need to create some classes to index. You can use plain old prototype classes:

function Person(name,age) {  
  this.name = name;
  this.age = age;
}
Person.prototype = new Entity();

Person = JOQULAR.createIndex(Person, true);

var p1 = new Person('Joe', 24);  
var p2 = new Person('Mary', 18);

Person.joqularSave();  

And then make a query like this:

Person.joqularFind({ name: 'Joe' });  

It's got an ODM feel to it, but you could technically index anything. This example is based on the example code from the wiki -- if you want to read more take a look at the JOQULAR API documentation and the patterns page.

JOQULAR works with Chrome and Node out of the box, but Firefox and IE need polyfills for Object.Observe.

angular-atomic-notify

Maxi Gimenez's angular-atomic-notify (GitHub: maxigimenez/angular-atomic-notify, License: MIT, npm: angular-atomic-notify) is an AngularJS library for presenting notifications. There's an ng-atomic-notify directive, and methods like atomicNotify.info(message, delay) and atomicNotify.error.

The samples use Font Awesome for icons, and the overall design looks Material Design-inspired to me.

Featured

ui templating apps angularjs

Fltspc, Mustache-Wax

Posted on .

Fltspc

Clint Heyer from the IT University of Copenhagen sent in Fltspc, which is a collaborative whiteboard. If you do group meetings where you want to work on snippets of text in a way that Google Docs doesn't quite cope with, then you might like to try this project out.

It can be extended with JavaScript and a REST API -- there's a GitHub repository with more information at ClintH/fltspc-client, and I also found an Android example.

Clint also shared a project they use to get students started with modern JavaScript development. It's called Kattegat, and it uses Yeoman and Express to get a server running with fun things like Socket.IO and Tessel.

If you're interested in Clint's Android work, then also take a look at Anders Bech Mellson's Kiosker project. This is a generator for Android kiosk applications that displays a single web page, and it's configurable through JSON. It sounds like this is what the students have been using to demo their interactive experiments on tablets.

Mustache-Wax

Mustache-Wax

Mustache-Wax (GitHub: jvitela/mustache-wax, License: MIT) by Jonathan Vitela is an extension for Mustache.js which allows you to use formatters inside expressions, in a style inspired by AngularJS. By defining a list of methods on Mustache.Formatters, you'll be able to pass values through the filters.

The expressions use pipes, and you can chain them like this: ten | add : 3.14159 | add : twenty | add:-3. The expression syntax supports arguments, which are denoted with :.

The documentation is nicely presented, and the project is well-tested.