Friday, January 18, 2013

Fixing JavaScript Intellisense completion

If you are doing a lot of JavaScript development, especially if you are doing SharePoint Apps development, you have come to love the great script IntelliSense feature in visual studio.

This gives you great auto-completion on client side objects and members and makes your development experience much better, especially if you are used to all this goodness from working with other rich languages like C#:


This auto-completion is easy to achieve, all you need to do is add a “_references.js” file and reference all script libraries in it:


Now, once you do some real JavaScripting – you will soon start working with prototypes, defining classes and instances and so on.

Once inside a method, you will notice that if you define a member inside the method it will keep the autocomplete working:


But once you start declaring and using class members, you will see a strange warning message and autocomplete will show you all known objects instead of just the relevant members for this variable type:


“IntelliSense was unable to determine an accurate completion list for this expression.
The provided list contains all identifiers in the file.”

The reason for that is, that if you define the variable member before this point, in the class level, and set it’s value later on in a constructor or other init method – Visual Studio does not know the type of object this variable is going to be set to, so it cannot build the correct auto-complete list.

The fix is simple, you can tell visual studio what type of variable you are creating by adding a ///<field> comment just above it’s definition:


And now, when we try to access this member again – auto-completion will work as expected:


The tricky part is finding out the exact type name for each variable. here are a few that I found, hope it would come in handy:

/// <field name="context" type="SP.ClientContext">Current client context</field>
/// <field name="web" type="SP.Web">Parent web hosting the app</field>
/// <field name="webInfo" type="SP.WebInformation">Parent web info hosting hte app</field>
/// <field name="lists" type="SP.ListCollection">current web lists</field>
/// <field name="list" type="SP.List">selected list (by _ListName)</field>
/// <field name="view" type="SP.View">selected view (by _ViewName)</field>
/// <field name="defaultView" type="SP.View">default list view</field>
/// <field name="query" type="SP.CamlQuery">caml query to run</field>
/// <field name="listItems" type="SP.ListItemCollection">result list item collection</field>
/// <field name="listItem" type="SP.ListItem">current list item</field>

if you want to find out the type name of other returned objects, you can alert() their “.constructor.getName()” value.

Have a wonderful scripting day!

No comments: