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 DateTime fields rendered using the jQuery UI datapicker control.
In this example, we have a SharePoint field with an internal name of WorkDueDate (and a corresponding attribute in our Backbone model) that we want to render using the jQuery UI datepicker 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="WorkDueDate">Due Date</label> | |
<input class="form-date" type="text" id="WorkDueDate" name="WorkDueDate" /> | |
// In your view... | |
// Stickit handler for the jQuery UI date picker plugin in SharePoint 2013 | |
Backbone.Stickit.addHandler({ | |
selector: "input.form-date", | |
initialize: function ($el, model, options) { | |
var opts = { | |
showOn: "both", | |
buttonImage: "/_layouts/15/images/calendar_25.gif", | |
buttonImageOnly: true, | |
buttonText: "Select date", | |
onClose: function () { | |
$(this).valid(); | |
} | |
}; | |
$el.datepicker(opts); | |
var changed = function (m, v, opt) { | |
// Optionally do something with changed value. | |
}; | |
this.listenTo(model, "change:" + options.observe, changed) | |
} | |
}); | |
// In your view's stickit bindings | |
"#WorkDueDate": { | |
observe: "WorkDueDate", | |
setOptions: { | |
validate: true | |
}, | |
onGet: "formatDate", // optional | |
onSet: "formatDate" // optional | |
} | |
// This helper uses Moment.js to format dates for use in SharePoint. | |
// This is optional, but helpful. | |
formatDate: function (value, options) { | |
return moment(value).format("MM/DD/YYYY"); | |
} | |
// For more details, see: | |
// http://sharepoint.softwaredevelopmentoutpost.com/2016/01/global-backbonestickit-handler-for.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