Category Archives: SharePoint JavaScript

Six Things to Know About the Newly Announced SharePoint Framework

Today at The Future of SharePoint event in San Francisco Microsoft made several important announcements and released quite a bit of information. Without a doubt, the new SharePoint Framework was the biggest bombshell. As a longtime SharePoint MVP and founder of an ISV that sells SharePoint add-ins and tools, I was fortunate to be in Redmond early in the process and more recently to offer feedback. In fact, I and my associate, fellow MVP Dan Attis, actually got to spend a few days playing with the new bits at a recent Dev Kitchen in exchange for our feedback. Here are my top six big picture thoughts on the new stuff.

#1: You Are Not Screwed

One thing that was immediately noticeable in my recent interactions with the SharePoint team is that they are excited. They believe in this stuff and they want to share their new awesomeness with you. They think you’ll love it as they do! For many of us though, the most likely initial reaction is to be very disturbed. It’s the kind of feeling I imagine a homeowner gets when she receives the Notice of Eminent Domain for the road widening that will destroy her front yard.

So, the first thing you need to know is that the existing UI upon which your house stands on is not scheduled to be bulldozed. SharePoint 2016 is not shipping with the new experience. The features it does ship with reach the end of mainstream support in 2021 and extended support in 2026. Those dates represent the earliest possible end of support.

But what about SharePoint Online?

There as well, you can expect to be able to use the current experience for a long time to come. The hybrid story depends upon it, but more importantly Microsoft has huge customers that are in the process of moving to SharePoint Online from on-prem environments based on the current UI.

In fact, if you have significant investments in custom solutions based on the current UI, you should be feeling a sense of relief. Most such solutions have some level of dependency on UI things Microsoft has said should not be depended upon and we all live with some level of fear that we will wake up one day to find one of the dependencies changed and our solution is broken. Microsoft’s new approach makes this much less likely.

The only reason to be concerned is if you are an ASP.Net Web Forms developer who hasn’t made moves to learn modern web development – in which case it is well past time you hit the books. I promise that it is easier than what you are doing now which is why the rest of us have moved on.

#2: It Restores a Key Value Proposition of SharePoint for SharePoint as a Platform

A big reason for SharePoint’s success is that it is based on ASP.Net Web Forms. Ten years ago, a big chunk of enterprise web developers used ASP.Net as their primary tool. This meant that SharePoint development was pretty approachable to many enterprise developers. Since then though, times have changed. New developers aren’t learning ASP.Net Web Forms. What was a big strength has now become a big weakness and traditional SharePoint development skills are niche skills in today’s job market.

This is a problem for everyone in SharePoint land that needs developers including Microsoft. There are people working as developers on the SharePoint platform who were not old enough to use the kitchen stove when ASP.Net Web Forms came out!

The new SharePoint Framework means that SharePoint development is now in step with mainstream web development once again, except this time you have a lot more choices. It also matters less what choices you make because the framework offers a better way to isolate your solution while also being as deeply integrated as is required.

Furthermore, the new framework embraces the fact that you need the ability to participate in the page’s real DOM. It no longer forces the use of things like iframes and weird URLs. You don’t need to be clever or go against the grain as is often required now to build the types of customizations required by the business you are in.

#3: Open Processes Work Better

I’ve been focused on SharePoint for a decade and I’ve been an MVP for the last five years. For most of that time what Microsoft intended to deliver was completely set in stone by the time anyone outside the SharePoint team knew what was coming. As a stakeholder, the best you could do was complain loudly in hopes that the thing will be better in three years when the next version comes out. In some areas, the Office development teams have fully embraced open source software and open development. In this case they opened up on the core platform for the first time and got feedback at several points in the process. I think the result will be much closer to ‘good’ out of the gate than I had previously come to expect because this time around I’ve actually seen them change their minds based on feedback from outside their own team!

I admire the SharePoint team for how far they have come in this regard. Opening yourself up to criticism is not easy. Personally, I hate it.

I could sense the stress at the Dev Kitchen. It must have been terrifying for each of them. At dinner on the last night, after what was clearly a successful event I could sense the relief. They’d deliberately put themselves through the wringer and survived, but they all looked like they were going to fall asleep!

Make no mistake – it is still early. The first releases of this stuff are guaranteed to have holes and annoying flaws, but things should improve quickly because…

#4: The Biggest Issue with Modern SharePoint as a Platform is Being Fixed

In my opinion, the single biggest factor with the limited success of sandbox solutions and the first versions of the app/add-in model was not that each lacked or blocked functionality that was easily accessible in farm solutions. No, the biggest issue with modern SharePoint as a platform is that the SharePoint development team did not use either model themselves. They had no real skin in the game and no internal incentive to fix what was always somebody else’s problem.

The SharePoint Framework does not just align SharePoint development with modern web development. It also more closely aligns the SharePoint development team with the developers who are customizing SharePoint. Unless they make a habit of cheating, the really big flaws are going to get fixed.

#5: Microsoft Needs Your Help

All that said, there is still some cause for concern. The document library preview release left many scratching their heads. The fact that they dropped something like into first release that without even putting it on the roadmap was hard to understand. And the absence of support for fundamental features we and PnP rely upon such as script custom actions or jsLink was just dumb.

Please note that I know dumb when I see it. As a very experienced and well-respected software developer and business owner I work in dumb like other artists work in clay or oil.

As an outsider it’s fun to speculate where that sort of dumb comes from. Is there a powerful manager that hates PnP and the rest of us so much that they would withhold a couple key lynchpins to see it fail? That would make a great story, but still, it is hard to believe one person could generate that amount of dumb. It probably required a whole team!

I believe that, for a long time, the SharePoint team generally thought that the use of either of these missing features was a hack that should be discouraged because script injection was bad and therefore they were bad. Perhaps now that SharePoint is embracing script injection people still subconsciously want to kill those features but don’t realize their ‘flaws’ are now seen as virtues. This a sort of diffuse cloud of dumb that is common in groups with a long history even where all of the individuals are very smart.

Or maybe the dumb wasn’t dumb at all. Maybe it’s the people focused on building the new document library had a narrow focus that didn’t include any integration scenarios.

Whatever the reason, feedback is to dumb as sunshine is to nasty germs. Their development process is now built to generate lots of feedback before delivering and act upon it. You can help by getting involved and giving lots of feedback in the public Yammer network and on SharePoint’s User Voice page.

Speaking of User Voice and the missing document library features…

#6: It’s not Vaporware

The Dev Kitchen I attended had several accomplished SharePoint development experts, but it also met a good number of people from ISVs who didn’t have much, if any, experience working with SharePoint. I saw people working in OSX, Linux, and Windows. There were a number of scripted hands on labs, but we also had free time to implement our own solutions. Over the course of three days I saw several really impressive samples from this diverse bunch of people.

As for myself, I took a moderately complex sample that uses AngularJS and Bootstrap for pluggable components and wrapped it in the new stuff. It took very little time, and the end result worked in both the current UI and in the new UI. I should probably mention that I was pretty unlucky and was in pain from a kidney stone during much of the event! Even in my diminished and pitiful state I was able to work completely outside the script and it worked!

Using the SharePoint Client Object Model in AngularJS Apps

A common problem for SharePoint developers new to AngularJS is using the client object model within the context of AngularJS scopes.

The Problem Explained…

If you already understand AngularJS, feel free to skip this part!

Consider a controller that displays the name of the current user.

<div ng-controller="IQAppPart">
  <div ng-if="!!UserName">
     <h1>Hello <span ng-bind="UserName"></span></h1>
  </div>
 </div>
 

If the $scope variable of the IQAppPart has a value for UserName the greeting appears.

The IQAppPart controller function looks like this:

var iqAppPartModule = angular.module(‘iqAppPartModule’, []);
var iqAppPartController = iqAppPartController || {};
iqAppPartController.IQAppPart = function ($scope) {
//Make a request for the user
var ctx = SP.ClientContext.get_current();
var user = ctx.get_web().get_currentUser();
ctx.load(user);

//Send the request to SharePoint
ctx.executeQueryAsync(function () {
    //Set the UserName
    $scope.UserName = user.get_title();
  }, function (error) {
    alert(error.get_message());
  });
};
iqAppPartModule.controller(‘IQAppPart’, [‘$scope’, iqAppPartController.IQAppPart]);

Notice the highlighted line. This sets UserName and you might expect that this would in turn cause AngularJS’s magic data binding to display the greeting, but instead nothing would happen.

The code will run without error and retrieve the UserName, but that’s all. The greeting will not display. The reason for this is hard to see if you are new to AngularJS because the code sets the $scope and the line that does it is inside the controller function!

To understand the problem you must first realize that the call to SharePoint, executeQueryAsync, calls the success handler when it receives the result from SharePoint. The function call is an asynchronous operation that AngularJS knows nothing about.

The second thing you need to understand is that Angular’s model binding expects all operations of interest to start within the confines of an Angular process. When a page that is using Angular starts an Angular app via the presence of the ng-app directive on an HTML element or by calling angular.bootstrap(element), Angular starts listening for events specified element (with the attribute or passed to the bootstrap function) and all of the element’s descendants. So, it knows about clicks and other events. Whenever one happens, it reevaluates the model and then updates the HTML view.

Adding a call to $apply() as shown below fixes the problem. The call to $scope.$apply() tells Angular that something has changed and that it should do its work.

var iqAppPartModule = angular.module('iqAppPartModule', []);
var iqAppPartController = iqAppPartController || {};
iqAppPartController.IQAppPart = function ($scope) {
 //Make a request for the user
 var ctx = SP.ClientContext.get_current();
 var user = ctx.get_web().get_currentUser();
 ctx.load(user);
 //Send the request to SharePoint
 ctx.executeQueryAsync(function () {
   //Set the UserName
   $scope.UserName = user.get_title();
   $scope.$apply();
  }, function (error) {
   alert(error.get_message());
  });
};
iqAppPartModule.controller('IQAppPart', ['$scope', iqAppPartController.IQAppPart]);
 

Calling $apply() in the context of a controller is a big sign that you are doing it wrong!

Instead we need a mechanism that makes ClientContext.executeQueryAsync() work like any other service in AngularJS so that Angular will know when it is time to reevaluate the models and update the views.

The Solution

The solution is a service factory that wraps executeQueryAsync using Angular’s $q
service. $q is a service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

//Angular service Wrapper for ClientContext executeQuery.
//The $q service makes it easy to wrap SharePoint's context.executeQueryAsync for use with Angular
var module = angular.module('iqPart', [])
 .factory('SharePointService', ['$q', function ($q) {
   var SharePointService = {};
   SharePointService.executeQuery = function (context) {
     var deferred = $q.defer();
     context.executeQueryAsync(deferred.resolve, function (o, args) {
       deferred.reject(args);
     });
     return deferred.promise;
  };
  return SharePointService;
}]);

To use the SharePointService we inject it into the controller and use it instead of ctx.executeQueryAsync as follows.

var iqAppPartModule = angular.module('iqAppPartModule', []);
var iqAppPartController = iqAppPartController || {};

iqAppPartController.IQAppPart = function ($scope, sharePointService) {
  //Make a request for the user
  var ctx = SP.ClientContext.get_current();
  var user = ctx.get_web().get_currentUser();
  ctx.load(user);
 sharePointService.executeQuery(ctx)
   .then(function () {
     $scope.UserName = user.get_title();
   },
   function (error) {
     alert(error.get_message());
 });
};
iqAppPartModule.controller('IQAppPart', ['$scope', 'SharePointService', iqAppPartController.IQAppPart]);
 

The end result is something like:

–Doug Ware

JavaScript for the C# Developer Part 8 – WTF is this?

Previous: JavaScript for the C# Developer Part 7 – Prototypal Inheritance

In JavaScript for the C# Developer Part 6 – Objects I promised to cover JavaScript’s very confusing treatment of the this keyword.

 

 

The this keyword

Many languages use the this keyword or something similar, e.g. Me in Visual Basic, to represent the current object instance. JavaScript does too (http://jsfiddle.net/DougWare/rX8JA/).

The preceding example shows that within an object this works exactly like you would expect based on experience with C#. In the object x, this is equal to x. In the object y, this is equal to y.

If only it were that simple

The way this works in the example is obvious, because whatsThis is defined inside both objects. It makes sense that this refers to the object. Unfortunately it is not always so obvious because of the flexibility JavaScript allows with functions. Consider this example (http://jsfiddle.net/kgJ87/).

This example shows three different object instances as the value of this within the function globalWhatsThis: x, y, and window. This is actually a byproduct of the syntax – from a runtime perspective; this example is essentially the same as the first example. The declaration of the whatsThis members in the two object literals assign the value of the globalWhatsThis variable (which is a function) to whatsThis. Even though the function is declared outside the objects, the runtime effect is that each object has its own copy of the function.

A very simple change to the object literals to invoke globalWhatsThis from the whatsThis member functions has a profound effect on the results (http://jsfiddle.net/DougWare/cZ6p7/).

DOM element events

It should be clear that using this inside a function that is not part of an object is dangerous because the functionality of the called function depends on the caller’s implementation. This problem is often encountered with DOM element events. Consider this example where a button’s onclick handler contains JavaScript to call a global function (attached to window) (http://jsfiddle.net/DougWare/w46yC/).

Contrast that example with one where the function is attached directly to the event (http://jsfiddle.net/DougWare/kdTDN/).

If you use the jQuery framework (or something similar) to manage events you won’t encounter this because the framework ensures this will be the element that raised the event. Either way, you should understand that this is the same syntactical illusion as before; the value of whatsThis (a function) is assigned to the element object’s onclick property and is therefore part of the button element object! If the function calls a function that is part of the window, this will be window (http://jsfiddle.net/DougWare/kSEwE/).

Bind

There are a number of ways you can control the value of this instead of just writing code that uses it and hoping for the best! Among these is the bind() method of the function object. Bind is available in most modern browsers, but it isn’t available in versions of IE before 9.0. However, you can add it if you need it or use a framework like prototype that includes it.

The bind() method takes an object as an argument and returns a new function bound to the object of your choice to use as this (http://jsfiddle.net/DougWare/e7fBy/).

Callbacks

The most common error I see with regards to this is its improper use in scenarios where the developer is attempting to share data between the function that sets up the callback and the callback function. The SharePoint CSOM documentation contains numerous examples of this type of error. Here is an example from http://msdn.microsoft.com/en-us/library/jj163201(v=office.15).aspx.

Every instance of this in the sample code refers to window and these are therefore global variables just waiting to cause issues when there are multiple instances of the callback waiting!

An easier to identify variation of this mistake is found in callbacks bound to event handlers. In this scenario, this is the DOM element but this is the window in the callback for reasons that you should now understand. Here is an example that demonstrates the issue with a couple of buttons that setup callbacks via the built-in setTimeout() function (http://jsfiddle.net/DougWare/vfR42/).

When you run this example and click the buttons, undefined displays twice after a short delay because this.someData is undefined – this refers to window.

Using bind() with callbacks

The previous example can be fixed to bind the button elements to the appropriate callback (http://jsfiddle.net/DougWare/KByPj/).

Keep in mind that bind takes any object as its argument. In the example I bound this (the button) but I could use any object I want to act as this in the callback.

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 7 – Prototypal Inheritance

Previous: JavaScript for the C# Developer Part 6 – Objects

In the previous post you learned that JavaScript has objects but not classes. The post demonstrates the use of a simple factory method to create a closure that contains an object’s private state and an object created via an object literal (http://jsfiddle.net/DougWare/3Z9M6/). I like this technique because it is simple, the way it works is clear, and it isn’t easy to screw up as is the case with constructor functions and the new keyword. However, it has a couple clear disadvantages:

  • There is no direct way to test the object to determine its origin
  • Every object produced by the factory has its own copy its methods and its use of memory is not optimal

For these reasons I only use object literals for occasions when there will only be a small number of instances of the object in question, ideally only one. This is usually the case, but a given system probably has a few objects of which many instances are created. For these objects a different approach is needed. Instead of creating these objects with literals I want to create them from named models that I can reuse and extend as needed. These models are called prototypes.

Class based inheritance versus prototypal inheritance

C# has classes. The structure of a given object instance is defined by its class. C# supports polymorphism via classes; one class inherits from another class and add to, or override, its parent’s definition. In C# all classes share a common ancestor, the Object class.

JavaScript does not have classes. Instead JavaScript objects serve the same role by acting as prototypes. New objects are created by copying existing objects. The existing object acts as a model that defines the new object. JavaScript supports polymorphism because you can modify the new object and use it as the basis of yet more objects. Instead of a class hierarchy, JavaScript has a prototype chain. At the top of the prototype chain is a common ancestor, a function named Object.

When you create an object literal you are inheriting from Object.

Every object but one has a prototype

The only object that doesn’t have a prototype is the top of the prototype chain, Object, just as Object in C# has no base class. The prototype of every object literal is Object. When you try to access a member of an object, JavaScript first checks the object for a member with the specified name. If it doesn’t find it, it checks the prototype, then the prototype’s prototype, and so on until it gets to the top of the prototype chain. If it isn’t found anywhere in the chain, it is undefined.

Confusing naming causes confusion

JavaScript functions have a property named prototype. The prototype property is not the function object instance’s actual prototype and it behaves differently in different browsers. Because of this, if you try to understand how prototypes work by focusing on this property, you may end up like this.


The best detailed explanation I have seen for all this is this article: Constructors considered mildly confusing. I am going to attempt to explain it without spending much time talking about what is going on under the covers and try to make things as simple as possible.

The key thing to remember is that the value of a function’s prototype property is not the function’s prototype – it is the object assigned as the prototype of objects created by the function when the function is a constructor. A function’s prototype property contains an object instance which is applied as the model to all object instances created by the function when the function is used as a constructor function via the new keyword.

Constructor Functions

To review, the previous post taught you that JavaScript includes the keyword new.
When JavaScript sees new in front of a function call the function is a constructor function. JavaScript creates a new empty object instance, executes the constructor, and returns a new object that contains the object as initialized by the constructor. All the constructor must do is use the this keyword to extend the new object instance with the desired properties and methods as follows (http://jsfiddle.net/DougWare/whx3L/).


This example illustrates that the redShirt object and the blueShirt object exist independently of each other and each maintains its own private state.

The problem with this example is that the constructor initializes the object’s members each time it is invoked. Every instance gets its own identical copy of the getColorSize function just as each would if I used an object literal returned by a factory method. This is where the prototype property’s object instance is beneficial.

An example of a constructor that takes advantage of a constructor’s prototype looks like this (http://jsfiddle.net/DougWare/QYpM6/).


In this example, the constructor, Animal, and the object, pig, have no members of their own. This is proven by using the hasOwnProperty function. hasOwnProperty tests to see if an object instance has a property that is part of the instance. If the property is part of the prototype chain, or if the property is undefined hasOwnProperty returns false. When the code invokes identify() it is invoking the function that is attached to the prototype because the instance does not contain a member named identify. The same is true of the name property, but when a new value is assigned to the instance’s name property, JavaScript adds the property to the instance and no longer needs to traverse the prototype chain (http://jsfiddle.net/DougWare/vGvfj/).


The prototype property is assignable and can be any object

In the examples above, Animal.prototype is extended one member at a time. However, because prototype contains an object instance, any object can be a prototype. Therefore, the example can be rewritten as follows (http://jsfiddle.net/DougWare/4DYGW/).


Extending the prototype, Extension methods

By now it should be clear that all instances created from the same constructor point to the same prototype instance. This is the reason that using prototype offers superior performance and memory usage when you have many instances of the same type of object. One implication of this is that changing or extending the prototype instance affects every object on the prototype chain (http://jsfiddle.net/DougWare/VE52D/).


An implication of this is that you can extend all of the built-in classes to add methods just as you can with extension methods in C#. JavaScript coerces the primitive types string and number to objects to allow access to their prototype objects. Douglas Crockford uses this technique to extend Object to create a simple object factory that works for any object instance (http://javascript.crockford.com/prototypal.html). You can see it in action in the next example (http://jsfiddle.net/DougWare/MJaXL/).


Multiple levels of inheritance

It is possible to have multiple levels of inheritance by applying the parent object’s prototype to the constructor function of the child object (http://jsfiddle.net/DougWare/nKYtW/).


I feel compelled to editorialize on this point. You should be suspicious of this sort of thing when you see it in a design. There are times when inheritance of this type is valuable, but in my experience this is uncommon. You should carefully weigh the complexity of this technique against the potential benefit of a simpler design.

Using instanceof and is isPrototypeOf to determine an object’s origin

There are times when you may need to test an object instance to determine its origin. Every object has a constructor property which is an object containing a prototype property. You can’t trust these values and you should not use them! Instead you can use the instanceof comparison operator to identify an object’s constructor. One of the benefits of instanceof is that you can test for any level of the prototype chain (http://jsfiddle.net/DougWare/RDQU2/).


The instanceof operator requires you to have a working reference to the constructor function for the right-hand side of the comparison. You may not have such a reference. As an alternative you can check to see if a given object is the prototype of another object with the isPrototypeOf method (http://jsfiddle.net/DougWare/fzSPm/).


In this example the constructor function is f(), but at the location of the test, f() is inaccessible and out of scope.

Conclusion

If you made it all the way through this post you probably get that using prototypes is much more complex than using object literals as described in the previous post. Limiting your use of this technique is a good idea if your code is to be used or maintained by developers who are likely to be confused by prototypes. If you only have one or two instances of a given object you definitely should not use this technique. If you will have many instances the performance and memory savings prototypal inheritance brings justifies the additional complexity.

This is the second to last post I currently have planned for this series. The final post will be about the very confusing this keyword. If you’ve made it this far, you should have no trouble understanding it!

Next: JavaScript for the C# Developer Part 8 – WTF is this?

Author: Doug Ware

Monkey Patched Hacking of SharePoint’s UI JavaScript

I need a little break from the JavaScript tutorials, so today I’m going to write something fun you can file under ‘necessity is the mother of invention’. Understand that what follows is not future proof and that it behaves differently in different versions of SharePoint. However, it is mostly the same between SharePoint 2010 and SharePoint 2013…

One of the holes in SharePoint’s JavaScript libraries is the lack of a direct ability to react to a user’s activities related to list items and forms. There are times when you may need to know that a user is viewing or manipulating items without resorting to server-side code. Fortunately, most of the time it is easy to hijack calls to the built-in JavaScript and insert code that does whatever you need. In one of my apps I use this technique to redirect to custom forms. This lets me leverage the stock list views but use custom list forms with no server-side footprint. Note that there are supported alternatives to this technique; you can specify custom forms for a content type via the server and client object models, but I had some special requirements that made those options less than desirable.

Init.js

SharePoint includes a file named init.js that contains a number of interesting functions that can be hijacked via a monkey patch. As you learned in JavaScript for the C# Developer Part 3 – Functions, JavaScript lets you treat functions just like any other type of variable. As a result you can change a function’s implementation by assigning a new function to the original function name. I explained this concept more fully in the post Monkey Patching and SharePoint / Office 365.

Here are the user interface elements and the useful functions they call that I have used this technique to intercept. Be advised that, unfortunately, there are some edge cases, like the infernal calendar view, that do things differently.

  • Edit Item ribbon button – STSNavigateWithCheckoutAlert
  • New Item ribbon button – NewItem2
  • Add link in list views – NewItem2
  • Item links in list views – EditLink2
  • Edit Properties ribbon button in document libraries and edit control block – EditItemWithCheckoutAlert
  • View Properties/View Item ribbon button and edit control block – EditItem2
  • Upload ribbon button in document libraries – EditItem2
  • Add Document link – NewItem2

Demo

Here is an example in a document library view in SharePoint 2013 Preview. I used a content editor web part to contain the following script (http://jsfiddle.net/DougWare/u83LV/).

When I select a document and click Edit Properties an alert displays before executing the original function.

If I view the properties the alert for EditItem2 displays.

 

Be careful with this technique. If you use it, be prepared to change when you upgrade to SharePoint 2016.

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 6 – Objects

Previous: JavaScript for the C# Developer Part 5 – Closures are Simple

In the posts on functions and closures the demonstrations illustrated procedural and functional programming techniques. JavaScript supports both of these styles, but JavaScript is an object oriented language. In fact unless a variable is undefined, null, boolean, string, or number it is an object. Functions, arrays, dates, and regular expressions are all objects and JavaScript even wraps the primitive types with objects for extensibility.

JavaScript is a classless language that supports inheritance through prototypes. The word prototype is a fancy way of saying ‘model’. Simply put, JavaScript lets you create new objects from existing objects instead of from classes. Prototypes will be covered in a future post. This one focuses on the basics of object creation and manipulation.

Collections of Name-Value Pairs

A JavaScript object is little more than a collection of name-value pairs. The name is a key and can be practically any string of characters. The value can be of any type including function. Values of type function are the only thing that distinguishes a method from a property. Unlike C#, JavaScript lacks property getters and setters. Many libraries, SharePoint’s CSOM included, follow a pattern that uses set_value() and get_value() methods to read and write protected values. However, this style is often a hallmark of a JavaScript library ported from another language, as is the case with CSOM, and is not necessarily a pattern you should follow.

You can access an object’s members by using dot notation (object.member) or square bracket notation (object[‘member’]). Since the size of scripts is generally a concern with web sites, the dot notation is preferred because it uses three less characters and most people find it more readable. One difference is that the bracket notation allows member names that are disallowed with dot notation. Another is that you can access members dynamically with square bracket notation as the following example shows (http://jsfiddle.net/DougWare/W6BcJ/).


In this example the object (remember that functions are objects) has a property named 2 + 2 == 4. Of course this would be a crazy thing to do in real life, but it shows how flexible JavaScript can be. This is in stark contrast to the amount of reflection code required to access a member via reflection in C# and it enables techniques seldom used in C# programs.

Creating Objects with Object Literals

The easiest way to create an object is with a literal expression with JavaScript Object Notation, JSON. In the JSON format the collection of name value pairs is wrapped in curly brackets, names are separated by a colon, and name value pairs are separated by a comma. If a name contains invalid characters, as in the example above, one need simply enclose the name in quotes. Here is an example (http://jsfiddle.net/DougWare/R5ufM/).


 
 

As you can see, JSON is very flexible! Since you can use any valid literal on the left side of the colon you can nest objects and include arrays (http://jsfiddle.net/DougWare/w5Ekn/).


 
 

This flexibility is a key reason so many people use JSON as a data interchange format preferred over XML.

The JSON Object

All of the popular modern browsers include a built-in object named JSON that includes two methods:

  • stringify() – Returns an object as a JSON formatted string
  • parse() – Returns an object from a JSON formatted string

It is worth noting that the JSON object ignores functions (http://jsfiddle.net/DougWare/7YWDg/).


Note that the alert contains an empty object for nestedObject instead of the doMath() function.

Constructor Functions

A function is a type of object. JavaScript includes the keyword new which creates a new empty object instance, executes the function as a constructor, and returns a new object that contains the object as initialized by the constructor. All the constructor must do is use the this keyword to extend the new object instance with the desired properties and methods as follows (http://jsfiddle.net/DougWare/whx3L/).


This example illustrates that the redShirt object and the blueShirt object exist independently of each other and each maintains its own private state.

This is my least favorite way to create objects – I really dislike how the new operator works because it simply changes the behavior of the function call and a call that accidently lacks new looks perfectly fine when you read it! This problem is easily seen in the following example (http://jsfiddle.net/DougWare/3VVzY/).


In this example the assignment to blueShirt is missing the new operator. The constructor function does not return a value and blueShirt is undefined, but the syntax is perfectly valid.

Another problem is that the value of this when new is missing is the window object. As a result, this.color and the other members of the object are attached to window and become global variables! (http://jsfiddle.net/DougWare/pkwrH/).


The behavior of this is one of the most confusing aspects of JavaScript and is the subject of a later post.

The Simple Object Factory Pattern

My personal preference is to use the object factory pattern and avoid the use of new. An object factory is a function that creates, initializes, and returns an object instance based on zero or more input parameters. There are a number of ways you can go about this in JavaScript and my way isn’t necessarily the best. Here are two alternative
approaches the latter of which being a full blown implementation of the pattern. I have no doubt someone will feel compelled to point out that what I’m showing here doesn’t fit the formal definition of the pattern.

My simple factory relies on a closure to give the instances private variables and an object literal to provide the scaffolding of the object. The object literal resembles a class. (http://jsfiddle.net/DougWare/3Z9M6/)


There is Another Way

…but I can’t explain it without first explaining prototypes which will be the topic of the next post, JavaScript for the C# Developer Part 7 – Prototypal Inheritance.

Until then, happy coding,
–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 5 – Closures are Simple

Previous: JavaScript for the C# Developer Part 4 – JavaScript’s Dangerous and Wild Type System

One of the problems C# developers have wrapping their brains around JavaScript is that there are a few concepts that don’t clearly map to what they already understand; concepts with scary names. Closures are one of those concepts. Wikipedia has an article on closures that I think illustrates this point rather well – it takes a relatively simple topic and makes it sound really complicated! If you understood what it says on first reading you have my congratulations.

In JavaScript for the C# Developer Part 3 – Functions, I showed a number of ways you can use functions to protect your variables from collisions with other scripts. The first example I used looks like this.


This protects the variable x within the two functions, but it only allows for a simple sort of execution – I have to call foo whenever I want to invoke bar! Furthermore, what if I want to use bar in many different contexts and I want each of them to have a unique value for x? This is where closures come into play.

A Closure is a Cocoon of Love that Protects your Variables

A closure encapsulates (creates a protected wrapper around) the contents of a function allowing the contents to exist after the function executes. All that is required is for the function to assign its internals to something outside of itself or to return its internals via the return statement. Here is a simple example of a closure in action (http://jsfiddle.net/DougWare/t87kB/).


In this example the function foo() is executed twice. Each time the function bar() is returned and assigned to a variable: first f1 and then f2. Both calls create a closure that creates a protected copy of the variable i for the use of each closure. Executing f1() twice alerts the values 0 and 1. Executing f2() twice does the same thing proving that each has its own distinct copy of i.

The Key is the Call

The only aspect of this that I have seen confuse people after they understand the first example is that they sometimes think the closure is unique to individual functions. But this example shows that even though there are three functions within the outer function, there is only one closure (http://jsfiddle.net/DougWare/SwAdg/).


Now, you probably read that example and thought, ‘gee that’s obvious!’ Alright smarty-pants, try this one (http://jsfiddle.net/DougWare/wEZvq/)!


In this example, which uses jQuery, there are two buttons. Each if these is bound to a function that increments a variable named x. What will you see when you click one button and then the other?

The answer is 1 and then 2. The buttons share the same instance of x from the closure created by document ready – $(function(){}); is shorthand for $(document).ready(function(){});

If what we want is for each click function to get its own copy of x we could rewrite the sample as follows (http://jsfiddle.net/DougWare/wEZvq/2/).


In this version the function that is invoked for each of the buttons creates a closure. Click the buttons to see that each has its own copy of x.

Conclusion

Closures provide an effective way to protect you variables and manage scope. They offer encapsulation, but closures aren’t the only way to achieve encapsulation. You can use objects… which is the subject of the next post!

Next: JavaScript for the C# Developer Part 6 – Objects

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 4 – JavaScript’s Dangerous and Wild Type System

In the previous posts about variables and functions I wrote extensively about how to manage scope and protect your variables from colliding with other scripts. The ease with which you can accidently create or affect global variables is one way JavaScript is like a long sharp piece of metal to be handled with care. This is especially important given JavaScript’s beautiful type system.


Types of types

Whenever I write anything based on presentations I go back and re-research the things I say in the talk. I do this because I might have been wrong about something I said and I can’t deny anything I put down in writing. The original slide deck for this series has a slide titled Primitive Types. When I began outlining this post I went out and tried to find an authoritative source to confirm what that slide says only to discover several sources that showed my slide to be slightly wrong! The problem was that these sources disagreed with each other!

Here is an article from MSDN, one from the Mozilla Developer Network, and one from Wikipedia. Each describe the subject of JavaScript types a bit differently and if you do the same research I did you will find many others. Finally I fell back on the ECMAScript JavaScript Language Specification which says that the primitive types are:

  • Undefined
  • Null
  • Boolean
  • String
  • Number
  • Object

That list is very interesting because as you saw in the previous post the result of typeof() for a function is ‘function’ (even though a function is really an object):


Just as interestingly, the typeof(null) is ‘object’ (even though null is really a Null):


Both of these results are proper and correct according to the spec for typeof in ECMAScript JavaScript Language Specification!

It’s important to understand that there is no such thing as an official JavaScript implementation. Just as with HTML and CSS, there is a specification and many individual implementations from different vendors. Furthermore, some of these implementations are quite old and have interesting quirks that are preserved for backwards compatibility. I have read that the behavior of typeof with regards to null is a manifestation of this.

Therefore, it seems that if I try to apply rigor to my discussion of the type system I will go down the rabbit hole into wonderland and focus on minute details and that is not the goal of these posts! For the purpose of this discussion I’m going to be a little lazy and simply focus on the types as described by the possible return values of typeof.

  • undefined
  • object
  • boolean
  • number
  • string
  • object
  • function

Undefined

When you declare a variable in C# you specify its type either explicitly via the declaration or implicitly using the var keyword based on the return type of an expression. In JavaScript a variable’s type is determined by its value. Furthermore a JavaScript variable’s type can change by assigning a value of a different type. Consider the following example (http://jsfiddle.net/DougWare/KrDtv/).


The typeof statement returns a string value with the name of the type. JavaScript also includes the named constant
undefined of type
undefined whose value is undefined. This is illustrated by the following boolean expression (http://jsfiddle.net/DougWare/NAGAr/).


You can test for the value undefined in a function with arguments to determine if the caller supplied an argument (http://jsfiddle.net/DougWare/MXaWB/).


The test for undefined in this example is safe because the existence of a variable named arg within the function’s scope is certain. However, in cases where the existence of a variable with a given name is not guaranteed you should always use typeof (http://jsfiddle.net/DougWare/2D3ds/).


If you test an undeclared variable for any value including undefined a runtime error is the result!

Null

JavaScript provides a named constant
null of type
object whose value is null. Null means that a variable exists, but that its value is unknown. There is a very subtle difference between a variable whose value is unknown and a variable whose value is undefined, but the former acknowledges that there is a value that is unknown whereas the latter just says a value was not supplied. Improper use of null is one of the hallmarks of a C# developer who is hacking together some JavaScript code. It is possible to rewrite a previous example and test for the presence of an argument by testing for null (http://jsfiddle.net/DougWare/wZVLD/).


This code looks correct and it works as intended, but it has two things wrong with it. The first is that it implies arg has some unknown value. The second is that it relies on the second biggest mistake C# developers make when they write JavaScript (after the accidental creation of global variables) – reliance on type coercion.

The Perils of Type Coercion, == Versus ===

Unless you already understood the reason, you were probably wondering why the examples of undefined used === but the example of null used ==. The answer is that === evaluates both the value and the type and is called the identity operator, but ==, the equality operator, attempts to coerce the types before the comparison. Consider this example (http://jsfiddle.net/DougWare/NPre7/).


This example should make it pretty clear how dangerous it is to rely on implicit type coercion. Furthermore, the math example might give you different results depending on the particular JavaScript engine that executes the code. Because the * operator only does multiplication, the runtime coerces x to a number and returns 25. However, the + operator does addition as well as string concatenation and in this case the runtime coerces y to a string and returns 55.

Many of the ‘JavaScript WTF?!’ examples I have seen rely on some sort of type coercion to achieve crazy results, but many examples like the test for null are relatively benign. That said, I always look for and flag == when I review JavaScript code.

Coercion in Boolean Expressions

The uninitialized values of the primitive data types evaluate to false when coerced in a Boolean expression, but they don’t all evaluate to true in other cases. The number 1 coerces to true, but other numbers evaluate to false. Boolean expressions that contain null or undefined values always evaluate to false unless you are comparing to null or undefined. Consider this example (http://jsfiddle.net/DougWare/xrGjV/1/).


Pretty weird eh? The key takeaway is that you should not rely on type coercion in your boolean expressions because the rules are bizarre.

Every Rule has an Exception

The one scenario where I think it is generally OK to leverage type coercion is when you need to initialize an argument to a function that wasn’t supplied by the caller. This technique relies on the fact that undefined values in boolean expressions evaluate to false in conjunction with the boolean or operator, | (http://jsfiddle.net/DougWare/uY6MR/1/).


Explicit Casts

The previous example is still a bit lazy because it doesn’t validate that the argument is a valid type, but in my opinion it is perfectly correct to throw an error if you expect a named argument to be of one type but the caller provides a different type. However, there are still many situations where you might need to cast a value, especially when you need a number from HTML text like the value of an input field. The basic cast functions are:

  • Number()
  • String()
  • Boolean()

Perhaps unsurprisingly, these don’t behave quite the same way their implicit coercions do (http://jsfiddle.net/DougWare/7hHjd/).


This post completely ignored objects. I’ll talk about those soon, but that I’ll go back to functions and examine the scary sounding but simple concept of closures.

Next: JavaScript for the C# Developer Part 5 – Closures are Simple

–Doug

Author: Doug Ware

JavaScript for the C# Developer Part 3 – Functions

Next: JavaScript Types

In the previous post I wrote about the basic scoping rules in JavaScript. There is more to say on that subject but first you need to understand the basics of functions.

The way JavaScript uses functions is very different from the way C# uses functions. JavaScript is a multi-purpose language that allows a variety of programming styles: procedural, object-oriented, and functional. This is because functions are incredibly flexible. This is one of the reasons I compare JavaScript to a sharp piece of metal with no safety features and a reason some people dislike working with JavaScript (especially other people’s JavaScript). The flexibility of functions allows syntax that is very confusing when approached from a strictly object oriented language like C# where functions are generally encountered only as members of classes.

In this post I will ignore functions as they relate to objects and save that discussion for later. For now I’ll focus on functions as procedures and as variables. As an aside, one of the best blog posts I’ve ever read on any subject is Steve Yegge’s incredible Execution in the Kingdom of Nouns. It is written as a criticism of Java, but it applies to C# as well. If you feel like you must have classes in order to write good code, you might want to read that post before continuing to open your mind to the alternative style that JavaScript supports (but does not enforce as it also has objects) before continuing.

Functions can Contain Functions

In the previous post I showed several mistakes that cause implied or unintended global variables. Nested functions provide a mechanism to prevent this and protect variables from being stomped by other script. Consider the following example (http://jsfiddle.net/DougWare/85MgV/).


In this example we have two functions, foo() and foo2(), each of which contain a variable named x and a function named bar(). If you execute the code you will see that foo and foo2 do not interfere with each other and that they neatly encapsulate their contents.

Functions can be Anonymous

An anonymous function is a function that has no name. If you’ve used jQuery you have almost certainly created anonymous functions most commonly with $(document).ready().


In this example the highlighted portion is an anonymous function that is passed as an argument to the ready() function which executes it when the document is ready.

Functions are First Class Types

As you can see above, the anonymous function acts like a variable. That’s because it is a variable and its type is function. You can see this by evaluating an anonymous function with JavaScript’s typeof() function. (http://jsfiddle.net/DougWare/k7Bsq/)


I can rewrite the example with an actual variable to get the same result. (http://jsfiddle.net/DougWare/BCQrk/)


Function Statements and Function Expressions

The function keyword actually plays two roles. In the first example the function statement defined the functions foo() and foo2(). An expression is an operation that is evaluated at runtime and yields a result. In the examples where the function is assigned to a variable or passed as an argument function acts as an expression. The difference is very subtle but important because function statements are hoisted by the JavaScript runtime to the top of the call stack prior to execution, but expressions are evaluated during execution in place. This is illustrated in the following example. (http://jsfiddle.net/DougWare/XMbUL/)


When this script runs the alert Statement appears and then a runtime error occurs. If you just run this in JSFiddle the effect is that the second alert doesn’t display. If you use a debugger you will see the error.


nonHoistedExpression is undefined because the function expression is below the attempted use of the variable!

Immediately Executed Function Expressions

The first example in this post works but is inelegant when we consider a script which we want to execute but which contains variables which we want to protect (and we always want to protect our variables). Since functions are first class types, functions can be anonymous, and function is an expression, it is possible to combine these concepts to create an immediately executed function expression. Consider this simple example. (http://jsfiddle.net/DougWare/8eC3p/)


In this example the anonymous function is wrapped by parentheses and followed with another set of parentheses that contains the function’s arguments (if any).

This means that we can rewrite the first example as follows. (http://jsfiddle.net/DougWare/QELHB/)


Using an Immediately Executed Function Expression to Prevent Collisions

The previous example protects our code’s variables and functions from colliding with other code, but it is also commonly used to improve the safety of frameworks like jQuery. The jQuery library maps the variable $ to the jQuery() function to as shorthand. It does so to help keep scripts that use jQuery as small as possible. However, jQuery is by no means the only library that uses $ as shorthand ($ is a legal variable name). Therefore, jQuery includes the noConflict() function which stops this mapping to prevent collisions. However, using this by itself means your script files will be bigger because you have to spell out jQuery everywhere instead of using the shorter variable $.

Immediately executed function expressions are commonly used to prevent this conflict globally while preserving $ for scripts that desire as shorthand for jQuery. For example: (http://jsfiddle.net/DougWare/4CxQw/)


Hopefully at this point you understand how you can use functions to manage scope and prevent collisions caused by global variables. There is more to cover on functions, but before that I’ll return to variables in the next post and talk about data types.

–Doug

Author: Doug Ware
(I’m trying out Google’s verified author system)

 
 

   

Author: Doug Ware

JavaScript for the C# Developer Part 2 – Variables and Scoping Rules

Next: JavaScript for the C# Developer Part 3 – Functions

If you are reading this post I probably don’t need to tell you what a variable is, but the chances are good that you misuse variables in JavaScript because as you learned in the first lesson, JavaScript is not C#!

Implied Global Variables

In JavaScript variables are declared using the optional var statement. The var statement declares a variable and optionally assigns a value. If you forget to declare a variable and simply use it, JavaScript will happily allow you to do so and will create a global variable as a result!

This behavior would be dangerous in any language, but it is especially dangerous in JavaScript because of <script> elements. Generally speaking, you have no way of knowing which other scripts might be used with your script when you are programming. This means that global variables are inherently dangerous. There is nothing to ensure that another script doesn’t make the same mistake and create accidental global variables. Two scripts using the same global variable name can easily collide and create interesting bugs.

Consider the script found here: http://jsfiddle.net/DougWare/yeDsf/ which illustrates the issue.


In this sample I have a script block that uses the variable I which is treated as a number. Elsewhere I also use a variable named I to which a string is assigned. Clicking the button yields:


It does so because I is not a number, NaN. In this example it is easy to see why this is so. In real life this type of defect can cause unpredictable behavior when scripts collide and can be very difficult to find! Another form of this problem is when you simply mistype a variable. If you transpose some characters JavaScript will happily make a new variable for you on the fly of global scope instead of producing a runtime error or warning.

Generally speaking JSLint will catch this problem and warn you that you have created an implied global variable.

C# has Block Scope, JavaScript does not!

Consider the following C# code:


This code results in a compile time error because C# has block scope and the code tries to use I outside of the block in which it is declared (the for block).

Similar code in JavaScript works.


Even though i was declared in the for block, it exists and is accessible even after the for block completes.

JavaScript doesn’t have block scope, it has function scope. Parameters and variables defined in a function are not visible outside the function, but a variable defined in a function is visible anywhere within the function. A function acts as a container and functions can contain other functions (more on that in another lesson). The key point is that a function can see the variables defined by its parent and other ancestors. These variables are ‘up-visible’ but because variables defined in a function outside the function, variables are not ‘down-visible’. This concept is easy to understand with this sample: http://jsfiddle.net/DougWare/jqYDH/.


Within the function inner() the variable input is visible because it is defined by its ancestor function top(). However innerVar is not visible from top() nor is top()’s named argument input visible outside the function top(). In both cases the test for undefined returns true because those variables are undefined at that scope.

Global variables are an Illusion

The fact that functions can see up implies that there must be an outer container that holds everything. This container’s name is window and it is not a function but an object. The window object provides the runtime context and contains properties that let you access things like the document and location as well as methods like alert and events like onload. Therefore, creating an implied global variable by forgetting var is the same operation as adding a member to window.


Global variables are just like local variables but they are local to window and thus visible everywhere to all of the functions contained by the window.

The Most Common Scope Related Error

Thus far you’ve seen two ways to create members on the window object, accidently by forgetting var and deliberately by using window. There is another far more common way that developers can create global variables and unintended name collisions.

Consider a page like this:


Where script.js is as follows:


Both the page and the script use variables named x and y and both use the var keyword. The browser reads and executes script.js first because it is at the top of the page. The script block at the bottom of the page executes last. When it executes the function foo() the output is not 4 but is abcd. This is because whenever you declare a variable that is not contained by a function it is attached to window!

This is easily the most common and dangerous issue with JavaScript code we encounter at our customers. The next post will cover functions and how we can use them to protect our variables.

Next: JavaScript for the C# Developer Part 3 – Functions

–Doug

Author: Doug Ware

Author: Doug Ware