A few months back, Ryan Niemeyer posted about a simple editor pattern for Knockout.js (anyone doing any significant Knockout development should be subscribing to his blog). Historically, I have used the “protected observable” which Ryan outlined in a post in 2011. In short, there are times when you are typing in a value and you need to ability to be able to “accept” or “cancel” user changes. The idea is that in addition the the observables for your object, you have 3 methods: 1) update() – which stores the latest values in a “local cache”, 2) revert() – which reverts the entire object back to the previous state, and 3) commit() which updates the “local cache” to the latest state.

The resulting code from Ryan’s post looks like this:

1: var Item = function(data) {

2: this.name = ko.observable();

3: this.price = ko.observable();

4: this.cache = function() {};

5:

6: this.update(data);

7: };

8:

9: ko.utils.extend(Item.prototype, {

10: update: function(data) {

11: this.name(data.name || "new item");

12: this.price(data.price || 0);

13:

14: //save off the latest data for later use

15: this.cache.latestData = data;

16: },

17: revert: function() {

18: this.update(this.cache.latestData);

19: },

20: commit: function() {

21: this.cache.latestData = ko.toJS(this);

22: }

23: });

This is an extremely useful pattern that is used frequently in Knockout development. However, I wanted a way to quickly and easily apply this to any object I was working with.

Lately I’ve been working with TypeScript so my thought was to create a base class in TypeScript that any class could inherit from to give the commit/revert functionality. This actually turned out to be quite easy with TypeScript. The first step is the create a base class called “EditableItem”:

The code is not much different from Ryan’s example but TypeScript let’s me work with class syntax. Notice I’m importing the TypeScript type definition file for Knockout – this can be found in the Definitely Typed repository. The revert and commit methods are practically identical. However, I wanted something more re-usable for assigning the values of the observables so I loop through each property of the data objects to do the assignment automatically. On line #24 above, the assignments happen by sending values into a function rather than assigning with the equals – this is because Knockout observables are all functions so we need to use function syntax. The JavaScript that TypeScript generates is not much different from the original example:

With this base class in place, it becomes a VERY easy matter to create sub-classes with this automatic functionality:

1: class Person extends EditableItem{

2: constructor(data: any) {

3: super();

4: this.updateValues(data);

5: }

6:

7: firstName: KnockoutObservableString = ko.observable();

8: lastName: KnockoutObservableString = ko.observable();

9: age: KnockoutObservableNumber = ko.observable();

10: }

This enables me to primarily just concentrate on my Person class without worrying about all of the plumbing details in the base class to make commit/revert work. Now we can use the Person object as follows:

You can customize this example even further for your application. For example, the constructor takes a data object typed as “any” but you could constrain this further – the underlying updateValues() function can still take any value. Additionally, you could consider passing the initial data object directly to the constructor of the base class – that is, pass it to the super() function. However, there is a major caveat you need to be aware of if you are thinking of going this route. Take a look at the generated JavaScript code for the Person class:

1: var Person = (function (_super) {

2: __extends(Person, _super);

3: function Person(data) {

4: _super.call(this);

5: this.firstName = ko.observable();

6: this.lastName = ko.observable();

7: this.age = ko.observable();

8: this.updateValues(data);

9: }

10: return Person;

11: })(EditableItem);

Notice the call to the super() function is the first thing that is called. Then after that is the assignments to the observable fields. After that is the call to the updateValues() function. Therefore, if you want to pass the data directly to the super() function, you’ll need to explicitly assign each field as an observable before calling the super() function to avoid the fields being null when the EditableItem’s updateValues() function is trying to assign the observable values. The class would look like this:

1: class Person extends EditableItem {

2: constructor(data: any) {

3: this.firstName = ko.observable();

4: this.lastName = ko.observable();

5: this.age = ko.observable();

6: super(data);

7: }

8:

9: firstName: KnockoutObservableString;

10: lastName: KnockoutObservableString;

11: age: KnockoutObservableNumber;

12: }

Ultimately, I didn’t favor this approach because it requires me to put extra lines of code in my constructor as compared to just initializing the observables inline. Either way, TypeScript enables rich scenarios for code re-use and helping better organize your JavaScript into object-oriented code.

There's a great library for this called "ko.editables" available on github ( https://github.com/romanych/ko.editables ) and also NuGet. It supports more advanced stuff like grouping multiple observables as a "transaction" (good for paged viewmodels) and I submitted a TypeScript definition file to the famed "DefinitelyTyped" collection on Github too (which is also on NuGet.)