To ‘this’ or not to ‘this’ with the Client Object model

24 Jul

Recently I developed a CustomAction on a list with some client script in the CommandAction. Nothing fancy or new.
I put a .js file in the _layouts folder and referenced the file by a CustomAction with Location ‘ScriptLink’ and ScriptSrc. Put some code in the file to get some data I needed and called executeQueryAsync with two delegates like this:

clientContext.executeQueryAsync(Function.createDelegate(this, this.OnSucceeded), Function.createDelegate(this, this.OnFailed));

Deployed as a Farm solution on the environment and everything went well so far.

After this, minds changed and it had to become a sandboxed solution. Ok, let’s do it.
1. Set the Sandboxed Solution property to True on the project
2. Removed the CustomAction with Location=’ScriptLink’
3. Put the code from the js file from the _layouts folder in the CommandUIHandler’s attribute CommandAction
4. Deployed the sandboxed solution

I always use FireFox when programming and all of a sudden I received the following error:
b is undefined

Client object model this FireFox

and things stopped working. While in the Farm solution the CustomAction worked as expected and the OnSucceeded and OnFailed were executed.

I put in some alert statements to see where the code broke and it seemed the OnSucceeded and the OnFailed methods weren’t executed at all.
By removing the ‘this’ keyword in the createDelegate everything went well again:

clientContext.executeQueryAsync(Function.createDelegate(this, OnSucceeded), Function.createDelegate(this, OnFailed));

This behaviour seems a bit strange to me. When putting the code in a separate js file and deploying it to the _layouts folder the ‘this’ keyword can be used, but putting the exact same code in the CommandAction of CommandUIHandler the OnSucceeded and OnFailed methods can’t be found anymore using the ‘this’ keyword.

By the way, in IE you will receive the following error:
‘b’ is null or not an object

Client object model this IE

2 Replies to “To ‘this’ or not to ‘this’ with the Client Object model

  1. Why not include the js file in a feature and deploy it to a (Style) library. Jan Tielens blogged about this a while back and the ScriptLink CustomAction supports ~SiteCollection in the ScriptSrc:

Comments are closed.