For those of you using Backbone.js and Backbone.Stickit for client-side SharePoint development, this is a quick article describing how to add a global Stickit handler for SharePoint Choice field rendered using the Chosen plugin for jQuery.
In this example, we have a SharePoint field with an internal name of WorkType (and a corresponding attribute in our Backbone model) that we want to render using the Chosen jQuery plugin through our Backbone view.
The following screenshot shows the end result:

In Stickit, we can create a global handler for specific elements (identified using standard selectors) that eliminates the need to manually create and attach 3rd-party controls outside of the normal Backbone and Backbone.Stickit flow.
Basic Steps
- Define the HTML in your view template.
- Add the global Stickit handler in your view.
- Define your Stickit bindings as you normally would. When stickit(this.model, this.bindings) is called in your view's render() function, the control is automatically created and attached to the appropriate element.
// In your HTML template... | |
<label for="WorkType">Request Type</label> | |
<select class="worktype chosen" id="WorkType" name="WorkType"></select> | |
// In your view... | |
// Stickit handler for Chosen plugin in SharePoint 2013 | |
Backbone.Stickit.addHandler({ | |
selector: "select.chosen", | |
initialize: function($el, model, options) { | |
$el.chosen(); | |
var up = function(m, v, opt) { | |
if (!opt.bindKey) $el.trigger("chosen:updated"); | |
}; | |
this.listenTo(model, "change:" + options.observe, up) | |
} | |
}); | |
// In your view's stickit bindings | |
".worktype": { | |
observe: "WorkType", | |
selectOptions: { | |
collection: function () { | |
var choices = [ | |
{ | |
"name": "Analysis", "value": "Analysis" | |
}, { | |
"name": "Design", "value": "Design" | |
}, { | |
"name": "Development", "value": "Development" | |
}, { | |
"name": "Testing", "value": "Testing" | |
}, { | |
"name": "Other", "value": "Other" | |
}]; | |
return choices; | |
}, | |
labelPath: "name", | |
valuePath: "value", | |
defaultOption: { | |
label: "Select...", | |
value: null | |
} | |
} | |
} | |
// For more details, see: | |
// http://sharepoint.softwaredevelopmentoutpost.com/2016/01/backbonestickit-handler-for-sharepoint.html |
The same technique can be used for a variety of client-side controls and plugins to simplify and add consistency to your SharePoint CSOM/JSOM code.
No comments:
Post a Comment