Select Page

Scot Hillier talks about leaving the developers with good solid ideas how to use and structure apps with JavaScript. The session purpose is to teach server side developers how to write JavaScript correctly, helps to introduce patterns to the apps in the new world.

JavaScript best practices

 

http://hillier.codeplex.com for the code

Coding practices

These are things to do good apps in the new model. It is important to establish these practices to make sure the apps that you build are easy to maintain and understand.

Strict mode

Declares using the "use strict" statement either at the top of a library or inside of a a function

Restrictions

  • Can’t use a variable without declaring it
  • Can’t write to read-only property
  • Can’t add properties to non-extensible objects
  • Can’t illegally delete functions and variables
  • Can’t define a property more than once in an object literal
  • Can’t use a parameter name more than once in a function
  • Can’t use reserved words, eval, or arguments, as names for functions and variables
  • The value of ‘this’ in a function is no longer the window object
  • Can’t declare function inside of statements
  • Can’t change the members of the ‘arguments’ array

Equality operators

Avoid coercive equality operators

==, != are coercive

===, !== are not coercive

Examples:

0 == ‘0’; //True
0 === ‘0’; //False
false == ‘0’; //True
False === ‘0’; //False

The problem with coercive is they try to work out what you mean, see the example where numeric 0 == text 0 is returned true. When this is not actually equals due to the data type.

This will save a lot of conversion bugs cropping up in code. (especially is C# is your background)

Encapsulation

Singleton Pattern – The declaration of a literal JavaScript object, which can have functions defined which can be invoked using method syntax.

Module Pattern – Self-invoking function ‘();’ at the end, the advantage is the public and private members to the object.

Prototype Pattern -Gives the developer a constructor, typically defining the member variables in the object. Then extend the prototype with the functions. The final element is the use of the ‘new’ keyword to create an instance with the prototype extensions.

If you need just one thing of something, then either Singleton or Module pattern are good. If you need a lot of something then the prototype is probably more appropriate. The prototype pattern is also more efficient, it will use the function on the prototype for every instance.

Promises

This becomes an important area of focus as a lot of the operations in apps are run asynchronously.

The reality for business apps is that multiple calls are going to be placed. So this is nowhere close to the hello world example of one call and one pair of methods to handle success and fails. This can lead to lots of nested calls. The second call relies on information in the first call, and can’t be made until it is retrieved.

Basically a ‘promise’ makes an async call but immediately returns an object, this object can be held and is the ‘promise’. This object then becomes filled with the data when it is returned. This object can also be held onto beyond the call which provides and interesting option for caching.

Also called ‘deferreds’

Simple async operations

The whole point of these is to avoid lots of spaghetti code.

Basic code pattern:

function myPromise() {
    var deferred = $.Deferred();
   
    setTimeout(function() {
        deferred.resolve("success");
    }, 1000);
   
    Return deferred.promise();
}

myPromise().then(
    function(value) {
        alert(value);
    }
    function() {
        alert("error");
    }
};

This is a jQuery example

jQuery offers the developer a $.Deferred function

The returned object in the first code block is within the developers method but it returns the jQuery object

The promise object has an implementation in the ‘then’ method

This function takes two function as args, the success and failure functions.

You can see from the code the removal for the need to nest calls and code.

So this is the basic approach, to take a deferred object and return it immediately, when things succeed, you call the resolve method of the deferred object. So this object will also hold the data, so there is no need to go back to the data source if the object data is already collected. This could be really useful when you think about people profile objects.

Demo

From the ‘Remote Endpoint App’

The example calls one RESTful endpoint for the album info and a second for the album art

Showed how in the app manifest the ‘remote’ endpoints were specified. These are cool because they allow the server to make the call to that endpoint for you.

If you are connecting to SP stuff or the SP host web you ask for permissions to do this during installation. Apps in SP are first class principals in SP2013, people authenticate with claims, apps use OAuth

This is one example for making a cross-domain call, when you specify a remote endpoint in the manifest for the app the call is actually made by SharePoint. So it’s made on the server side, the results are then relayed to the app. This is neat as it means the call is no longer cross domain.

In the musicbrainz.songquery.js file there is an example of calling this declare RESTful endpoint

Note: If you think you might be calling libraries which might not be using ‘use strict’ then put it in your function instead of your library.

To make this call through SP you have to use the ‘SP.WebRequestInfo()’

The code actually making the call to execute the code above is in ‘musicbrainz.songviewmodel.js’

Interesting observation that all the deferred objects are kept in an array

In the load function the code checks to see if the code has already been executed

The code matchs on the artist names in the held promises

If it was found the code sets the active promise to the one found

Be careful to use the ‘new’ keyword to make sure that instances are created or the code would go a little bit mental.

It then calls the ‘then’ method on the active promise

This block contains both success and fail logic

The patterns are really nice as the endpoint interactions are in a very clean library. This is really focusing this code on just the call, the display logic is factored out away from the data call. Really very well done, as you would in the C# world of MVC or MVVM

Note: Rob Bouge is building a ‘promise’ library over the SP REST calls

Libraries

Segregate code into libraries, there is a balance, due to efficiency of download, so maybe some go back together to make them faster to download.

Note: there is probably something for CKSDev as a feature for this

Minify those libraries so they download a lot faster, there are tools to do this

Consider the use of a CDN, how they get to the end user, a CDN is better for versioning

Load the SP libraries dynamically

Example code:

$(document).ready(function () {

hostweburl =
    decodeURIComponent(
        getQueryStringParameter("SPHostUrl")
    );
   
appweburl =
    decodeURIComponent(
        getQueryStringParameter("SPAppWebUrl")
    );
       
var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", onSuccess);
   
});

This is a good technique to get the SP libraries

Demo

Code is in ‘ContactsApp’

Note: the App project has a file called _references.js which is used to reference the scripts and get intellisense from the library

So the intellisense comes from this references file but the actual page references the debug versions

App Best Practices

REST

REST
This is the approach for web services
Uses a URI to completely specify the operation

OData
Maps CRUD operations to HTTP verbs GET, POST, PUT, DELETE, PATCH
Odata is an implementation of RESTful principles

Recommendation is JavaScript against REST and MVVM for on-premises and cloud

Second option is MVC4 and c# client side object model approach for those who don’t want to learn and write JavaScript. This of course means using provider hosted apps, which are more complicated.

_api replaces _vti_bin/client.svc

Two main ways to make RESTful calls

    1. $.getJSON – is a simplified way to make a RESTful call, normally one liner and returns a JSON object. This object has the kind of dot properties C# developers will like. This makes much more sense than returning just XML as it doesn’t require parsing into something useful.
    2. $.ajax – This is mainly just a longer version of JSON. Note the header is "application/json;odata=verbose" which not all examples will give but is best to use. If you don’t get this right the server will fail the request.
   
Basically as a REST programmer the entire focus is on the correct URI for the data

Note: a cool endpoint to return the viewing user is ‘/_api/web/currentuser’

Model-View-ViewModel pattern

Model contains data

View presents the data

ViewModel binds the Model and the View

The purpose is to separate the display from the data collection.

It works really well in JavaScript

The ViewModel fills the Model with data and then sends it to the view for display.

The best way to implement this is to use a third party library

Knockout.js http://knockoutjs.com

Features declarative bindings between elements in the code and pages (like old skool data binding) and dependency tracking

Pointed out the cool thing is the ‘ko.observableArray()’ which is the data and changes will trigger a page redraw

App UI guidelines

App project template – The VS template will already have some SP feel

WebTemplate – Apply a template

Chrome control – If just html page is being used, so use the chrome control

Custom Branding – Roll your own styling

Summary

This session had some useful patterns that can be recognised from some of the server-side patterns used in traditional SP development. The session left a lasting impression about the importance of well structured app JavaScript and what benefits it could bring to the developer.