Attaching to saving and saved events of a Work Item in a Custom Control

We have been asked lately about whether it is possible to do something before or after save operation of a work item inside a custom control. The answer is, yes, you can do that.

When a change occurs in a work item, there is actually a lot of events fired like field change, revert, saving, saved, etc. All you need to do is subscribing to the work item change event and then applying appropriate filtering on the change type when the work item is bound to the form (bind event of all controls on the form is called when a work item is bound to a form).

Please do not forget unsubscribing during unbind. Also note that these are all read-only notifications which means none of them can be cancelled.

Let's see some code:

 bind: function (workItem) {
    this._base(workItem);
    this._workItemChangeDelegate = function(sender, args) {
        if (args.change === "saving") {
            // Do something...
        } else if (args.change === "saved") {
            // Do something...
        }
    }
    
    // Delegate enables the specified function to run under current custom control's context
    // so that you can access other methods inside _workItemChangeDelegate 
    workItem.attachWorkItemChanged(TFS.Core.delegate(this, this._workItemChangeDelegate));
}

unbind: function (workItem) {
    this._base(workItem);
    workItem.detachWorkItemChanged(this._workItemChangeDelegate);
    delete this._workItemChangeDelegate;
}

 

And one last comment about "Save & Close". The above events are fired from Object Model but  "Save & Close" happens in UI level which prevents custom controls to attach that event. Because we do not have any API's for UI commands, it is not possible to intervene. Sorry for any inconvenience.

Hope this code piece helps and let us know if you have any questions or feedback.