Select Page

Scot Hillier talks about the massive investment that SharePoint developers have made learning the server object model and how with the new ‘apps’ being mainly client side technology brings the need for fast paced upskilling.

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 is now a CORE development skill for SP

Code from from all Scot’s sessions is at http://hillier.codeplex.com

JavaScript

Basics

Arguments are passed in arguments[], meaning you don’t need to match the function signature like in c#

JavaScript is object based, this is good in fact as it allows patterns of implementation that make us comfortable in the way we structure code

JavaScript Functions are objects too, this is a VERY IMPORTANT concept

JavaScript is case sensitive

Semi colons are optional but should be used

Variables are only created using the var keyword

Global namespace

This is where all the bad stuff begins when JS starts to be written

For SP developers the global namespace is in the ‘window’ object of the DOM

This matters as any variable declared outside the functions are declared into this namespace, this means you are putting something onto the window object.

Any variables defined without the var keyword are also in the global namespace, this is bad if you forget ‘var’ in a function it will end up in the global namespace

This WILL bite you because of name collisions

Technique

  • Use our own namespaces
  • Always use strict mode, this puts a lot of restrictions onto the JS code. He describes it as a ‘better’ version of JS

Custom namespaces

JS doesn’t have the idea of namespaces like c# does

The technique to do it is to create just one variable into the namespace

Window.Wingtip = window.Wingtip || {};

Basically either checks for an existing object or creates a new one for you
This would be an empty object

This is really good as you now have a ‘big’ container bound to the global namespace where you can avoid clashing with other namespaces

You can nest namespaces by adding others to the existing for example

Window.Wingtip.Singleton = window.Wingtip.Singleton || {};

Objects are just key value pairs

You can then also create an instance of an object and use the value as a function for example

Wingtip.Singleton.Customer = {
Name: “Brian Cox”,
Speak: function () { alert(“my name is ” + this.name); }
}

This code has created the object with name and speak, where speak is a function

This allows a call like this

Wingtip.Singleton.Customer.speak();

Which would fire the alert

Goal

  • To write clean JavaScript inside of namespaces

Functions

Functions are objects

They can be stored in variables, objects and even arrays

They can be invoked directly

There are 4 ways to call a function:

  1. Function pattern
  2. Method pattern
  3. Constructor pattern
  4. Apply pattern

These lend themselves to pattern development

Functions have a ‘this’, just like c# what ‘this’ points to is really important in the code

Function Pattern

This is the most common and worst way to invoke a function

function add(x, y) {
If(this===window)
Alert(“this is bound to the window, why???”);
return x+y;
}

Var sum = add(5, 6);

The reason this is so bad is that it is defined in the global namespace, which means the dev has to hope no-one else also has an ‘add’ function

The last guy to define wins

Method Pattern

We saw this above

Wingtip.Singleton.Customer = {
Name: “Brian Cox”,
Speak: function () { alert(“my name is ” + this.name); }
}

Wingtip.Singleton.Customer.speak();

When a function is contained within an object we can invoke it like a method

Even if the developer only uses this pattern you would be light-years ahead technique wise to the Function Pattern approach developers

Constructor Pattern

var Customer = function (name) {
this.fullName = name;
};

Customer.prototype.speak = function () {
Alert(“my name is ” + this.fullName);
};

var customer = new Customer(“Brian Cox”);
customer.speak();

JS objects can have prototypes, these define what the object will have
These are kind of like a c# constructor

The first section is just defining the function as a variable

Function object has an underlying object prototype

The second section is adding a new member to the underlying prototype members (like extending it)

The two ‘this’ lines refer to the first object instance of Customer

So you basically start by defining the constructor to create an instance of the object. The first section. Then extend it with members against the prototype. The second section. And finally you can get to call it 🙂 using the ‘new’ keyword

So it gets passed the name, then calls ‘speak’

This is an interesting pattern as it is pseudo OO

Some people have the opinion that this pattern misleads because it pretends to be OO

Apply Pattern

var Customer = function (name) {
this.firstName = fn;
this.lastName = ln;
};

Customer.prototype.speak = function() {
Alert(“My name is ” + this.firstName + ” ” + this.lastName);
};

var nameObject = {
firstName: “Brian”,
lastName: “Cox”
}

var customer = Customer.prototype.speak.apply(nameObject);

The apply pattern is the opposite of the method pattern

So the key difference is that the constructor is only the variable members, the prototype is then extended with the functions

Then a var object is created with the contents required for the ‘constructor’ params in the first section.
The apply then applies the object to method

This is not used all that often

Closures

Key concept

A closure is a concept of nesting functions… the inner function can access the variables of outer functions

If the inner function has a longer lifetime than the outer function, the variables they access are still in scope
This is explained in the Module Pattern notes

Module Pattern

window.Wingtip = window.Wingtip || {};
Wingtip.Module = Wingtip.Module || {};

Wingtip.Module.Customer = function () {

//Private members
var name,
setName = function (n) {name = n;},
getName = function () {return name;},
talk = function () {alert (“My name is ” + name); };

//public interface
return {
set_name: setName,
get_name: getName,
speak: talk
}
}();

The last line is important as the ‘();’ means it becomes a self invoking function

So if you ignored the content of the Customer function for a moment, what is the function equal too? Well it becomes equal to the return value of the function

So in the code sample the code returns the literal object under the comment //public interface which is the three member function objects defined under the private members comment

This means that the return is basically returning the inner functions as a return value of the outer function

You return the inner functions so the outer function is no longer in scope. Therefore the pointers for the inner functions are still in scope

This means you could still call ‘talk’ and it would run

This is one of the most common patterns and you will see it over and over again

What is cool about it is like treating it like a class.

So you can define all the pseudo class members as private variables

The only ones that become public to the calling object are the ones you choose to return via the return object

So now you can introduce the idea of hidden private code

So you can see in the example that although name is defined it is not returned so no-one can touch name so they have to call the get and set functions. This is a really good way to make your code more reusable

Demo

Takeaways

Opinion that even on-premises the SharePoint hosted app is the easiest as the other option of provider hosted adds complexity of setting up the other infrastructure like the IIS, load balancing etc

A SharePoint app is an ALL JS thing

His first demo was a singleton pattern to read back the web membership information
This is a useful pattern when performing RESTful calls as you don’t really need instances of this object

He’s been using jQuery but didn’t explain it during the session.

Two things it does really well

1. Allows selection of things in the DOM
2. Allows actions to be performed upon them

Both actions with far less code than if you wrote the code directly to modify the DOM

Developers will use the $.ajax calls to make the RESTful calls

Singleton Pattern

The pattern used has the following:

Init function
1. Which takes a parameter ‘element’ which is basically the jQuery element where the results should be shown
2. Sets the url of the RESTful endpoint (the _api bits)

Note: the _spPageContextInfo is an object which has been part of SP for several versions and is injected into the page by sharePoint. In the example the webAbsoluteUrl is used

Load function
1. Use the jQuery ajax $.ajax
2. As the call is async you have to provide both success and failure functions

onSuccess function puts together the HTML table of the results
onError function shows the error message

Note: the “use strict”; at the top makes this file strict

This whole logic is invoked at document.ready so the DOM is ready

Module Pattern with self-invoking function

Demo’d the }(); being the giveaway that it is a self-invoking function

The logic contained create/update/remove functions from the public return

Pointed out that the pattern will remain constant it’s the list that is changed per use, even applies to other things like the search endpoint.

Important: Made a big deal about taking this code from the CodePlex examples to make sure as a dev you can ramp up super quickly.

HTML5

 

The major browsers all now support HTML5 or at least the vast majority of things available to the developer.

Note: Strong belief that the bias should be towards HTML5 with some concerns to lesser experiences

What people mean when they say HTML5

  1. Combination of new tags in HTML
  2. Combination of new styling in CSS3
  3. New JavaScript functionality like geo-location

Semantic markup

This introduces a bunch of new tags, that are trying to specify the semantics of parts of the page

<nav> (where you would put your navigation)
<article> (could be the stuff you want to syndicate for RSS as an example)
<header> (the header)
<section>
<aside> (used for sidebars)
<figure><figcaption>
<summary> (summaries for sections)
<footer> (the footer)

This semantic mark-up is orientated towards the publishing types of information being presented on the page.

If you start to use the semantic mark-up it will make it easier for a search engine to understand the page.

Forms

HTML5 brings lots of new capabilities for forms

Types

  1. Color
  2. Date
  3. Date Time
  4. Email
  5. Month
  6. Number
  7. Range
  8. Search
  9. Telephone
  10. Time
  11. URL
  12. Week

Attributes

  1. Autocomplete
  2. Autofocus
  3. List
  4. Max
  5. Min
  6. Step
  7. Multiple
  8. Pattern
  9. Placeholder
  10. Required

These add new input types instead of just the plain old textbox.

Demo

Shows the new form mark-up and functionality

Code is in the ‘ContactsApp’

Pointed out in HTML5 that forms are ok inside layout tables, wasn’t sure if this was a sarcastic comment or reality.

Multimedia and Graphics

Multimedia for Audio and Video

Graphics for Canvas and Scalable Vector Graphics

Demo

Code is ‘Paint’ which demos the canvas app

Shows a load of the cool things that a canvas can do

Data and Functionality

Data

  1. Application cache – provides a cache in the JavaScript app
  2. Indexed DB – provides a mini database the JavaScript app can use
  3. Local storage – provides a persistent form of storage
  4. Session storage – provides local storage just for the session

Functionality

  1. Drag and drop
  2. Geolocation – provides the browsers location for use in the app
  3. History – provides access to the browser history properly
  4. Web workers – allows spawn of new thread in javascript, and execute a library on it
  5. Post Message – allows the sending of a message from the hosting web page into an iFrame or from an iFrame into a host page. SharePoint relies on this very heavily. This is how the app part model works.
  6. Web sockets – allows socket communications from apps

Demo

Geolocation and weather

Code is ‘WeatherBug’

Code shows a good example of how this geolocation should be used.

CSS3

 

A whistle stop tour of CSS3

Backgrounds and Borders

Loads of new styling capabilities

Backgrounds

  1. Background size
  2. Multiple backgrounds

Borders

  1. Border image
  2. Border radius
  3. Box shadow
  4. Text shadow

Graphics

  1. Animations
  2. Gradients
  3. Reflections
  4. Transforms

Demo

Showed an example of browser detection to make sure that you can cater correctly

Code is ‘DetectCapabilitiesApp’

Uses ‘Modernizr’ script library
(www.modernizr.com)

The ‘Detect Capabilities App’ shown has a display for the current browser which returns the results of each capability check from Modernizr.

Summary

 

I found the session really useful. As someone who has spent the last five or more years mastering the serverside object model and SharePoint an introduction like this was really helpful.