Using This And Bind() Correctly In Sharepoint Jsom Callbacks
The Problem with Losing “this” Context
When working with the SharePoint JavaScript object model (JSOM), it is common to pass callback functions to asynchronous methods to handle the response. Inside these callbacks, the meaning of “this” can change, causing errors.
For example, say we make a call like:
var context = new SP.ClientContext(); var web = context.get_web(); web.get_title(function(title) { // Error! "this" is now the global window object this.log(title); });
The callback loses the context of the SP.ClientContext instance, so “this” inside the callback refers to the global window object. Attempting to call this.log() fails.
How Bind() Allows You to Preserve “this”
The bind() method creates a new function where “this” is bound to a given value. Calling web.get_title() with a bound function preserves the original “this” context.
var context = new SP.ClientContext(); var web = context.get_web(); var boundFunction = function(title) { this.log(title); }.bind(this); web.get_title(boundFunction);
Now “this” inside the callback correctly refers to the context variable, allowing us to call this.log().
Basic Usage of Bind()
The bind() method accepts an object to bind as the first parameter and any parameters for the target function as subsequent parameters:
var boundFunc = func.bind(thisObj, param1, param2);
To properly bind “this”, pass it as the first parameter when calling bind():
var context = new SP.ClientContext(); var boundFunc = function() { // do something with context }.bind(context);
Passing Arguments with Bind()
You can pass arguments to the bound function by listing them after the thisObj parameter:
var addNumbers = function(x, y) { return x + y; }; var addFive = addNumbers.bind(this, 5); addFive(10); // Returns 15
This partially applies the function by fixing the first argument to 5. Useful in callbacks:
var web = context.get_web(); web.get_title(function(title) { // title bound as first callback parameter processTitle(title); }.bind(this, title)); function processTitle(title) { // do something with title }
Examples of Using Bind() in SharePoint Callbacks
Loading User Profiles
var context = new SP.ClientContext(); var peopleManager = new SP.UserProfiles.PeopleManager(context); peopleManager.getMyProperties(function(props) { // "this" bound to peopleManager this.load(props); this.executeQueryAsync(function() { // callback code here }); }.bind(peopleManager));
Getting List Items
var list = context.get_web().get_lists().getByTitle('My List'); var query = new SP.CamlQuery(); // create query list.getItems(query, function(items) { // process items }.bind(this));
Updating List Items
var listItem = list.getItemById(1); listItem.set_item('Title', 'New Title', function() { this.executeQueryAsync(); // bound to client context }.bind(context));
Calling SharePoint Methods While Preserving “this”
A common pattern is to call a SharePoint method in a callback while preserving the thisObj context:
var context = new SP.ClientContext(); var list = context.get_web().get_lists().getByTitle('My List'); list.getItems(query, function(items) { this.load(items); this.executeQueryAsync(function() { // process results }); }.bind(context))
First bind “this” to the context. Inside the callback, call context methods load() and executeQueryAsync() to process the results.
Referencing the Correct “this” When Nesting Calls
When nesting calls, each level can bind “this” as needed:
var context = new SP.ClientContext(); getData(function(results) { prepareData(results, function(preparedData) { // Nested callback binds this to context saveData(preparedData, function() { this.executeQueryAsync(); // context method }.bind(context)); }.bind(this)); // outer thisObj }.bind(this));
Here thisObj depends on the nesting depth. The innermost callback binds this to context while outer callbacks preserve their own object.
Common Mistakes to Avoid
Some common mistakes when using bind():
- Forgetting to pass the thisObj as the first parameter
- Binding to the incorrect context
- Calling bind() without storing the result to a variable
- Binding unnecessarily instead of using an arrow function
For example:
// Forgets to pass thisObj web.get_title(function() {}.bind()); // Binds to wrong context web.get_title(function() {}.bind(window)); // Doesn't store bound function web.get_title(function() {}.bind(this)); // Arrow function preserves this web.get_title(() => { // Can already use this });
Best Practices for Using Bind()
- Bind callbacks inline instead of wrapping in a separate named function
- Use arrow functions over bind() when possible to avoid extra processing
- Always store the result of bind() to a variable or pass directly to the callback
- Bind only the minimum needed – don’t overuse bind() unnecessarily
In summary, use bind() selectively when needed to preserve context in SharePoint callbacks. Prefer arrow functions where the existing thisObj is fine.