SharePoint: Enable/Disable ribbon button based on condition

Scenario: Enable/Disable ribbon button if the number of selected items is greater than zero and if versioning is enabled in the given list.
Solution:
EnabledScript property of CommandUIHandler can be used to specify the javascript function which will return true or false.
<CommandUIHandlers>
<CommandUIHandler
Command="ExportVersionHistory"
CommandAction="javascript:alert('Enable disable demo');"
EnabledScript="javascript:EnableDisableButton();"/>
</CommandUIHandlers>
The js file can be specified in CustomAction like this:

<CustomAction Id="Ribbon.Library.Actions.Scripts"
Location="ScriptLink" ScriptSrc="/_Layouts/Demo/EnableDisable.js" />

In the js file we will have following functions:

function listSuccess(sender, args) {
    this.versioningEnabled = this.list.get_enableVersioning();
    RefreshCommandUI();
}

function listFailed(sender, args) {
    alert('request failed ' + args.get_message() + 'n' + args.get_stackTrace());
}
function EnableDisableButton() {
    var items = SP.ListOperation.Selection.getSelectedItems();
    var ci = CountDictionary(items);
    if (ci > 0) {
        var context = SP.ClientContext.get_current();
        this.list = context.get_web().get_lists().getById(SP.ListOperation.Selection.getSelectedList());
        if (this.versioningEnabled === undefined) {
            context.load(this.list);
            context.executeQueryAsync(Function.createDelegate(this, this.listSuccess), Function.createDelegate(this, this.listFailed));
        }
        return this.versioningEnabled;
    }
}
profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+