Posts
201
Comments
1110
Trackbacks
51
An Editor Pattern for Knockout.js Using TypeScript Inheritance

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”:

   1:  /// <reference path="knockout.d.ts" />
   2:   
   3:  module EditableExample {
   4:      export class EditableItem {
   5:          private cache: any;
   6:   
   7:          constructor() {
   8:              this.cache = function () { };
   9:          }
  10:   
  11:          revert() {
  12:              this.updateValues(this.cache.latestData);
  13:          }
  14:   
  15:          commit() {
  16:              this.cache.latestData = ko.toJS(this);
  17:          }
  18:   
  19:          updateValues(data) {
  20:              this.cache.latestData = data;
  21:   
  22:              for (var property in data) {
  23:                  if (data.hasOwnProperty(property) && this.hasOwnProperty(property)) {
  24:                      this[property](data[property]);
  25:                  }
  26:              }
  27:          }
  28:      }
  29:  }

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:

   1:  var EditableExample;
   2:  (function (EditableExample) {
   3:      var EditableItem = (function () {
   4:          function EditableItem() {
   5:              this.cache = function () {
   6:              };
   7:          }
   8:          EditableItem.prototype.revert = function () {
   9:              this.updateValues(this.cache.latestData);
  10:          };
  11:          EditableItem.prototype.commit = function () {
  12:              this.cache.latestData = ko.toJS(this);
  13:          };
  14:          EditableItem.prototype.updateValues = function (data) {
  15:              this.cache.latestData = data;
  16:              for(var property in data) {
  17:                  if(data.hasOwnProperty(property) && this.hasOwnProperty(property)) {
  18:                      this[property](data[property]);
  19:                  }
  20:              }
  21:          };
  22:          return EditableItem;
  23:      })();
  24:      EditableExample.EditableItem = EditableItem;    
  25:  })(EditableExample || (EditableExample = {}));

 

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:

   1:  var person = new Person({ firstName: "Steve", lastName: "Michelotti", age: 21 });
   2:  person.commit(); // commit current state
   3:  person.revert(); // reverts to previous state

 

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.

posted on Monday, May 6, 2013 5:32 PM Print
Comments
Gravatar
# re: An Editor Pattern for Knckout.js Using TypeScript Inheritance
Alex Dresko
5/9/2013 8:55 AM
BRAVO!!! Makes me want to write a similar blog post on how I use TypeScript inheritance to hide lots of boilerplate code in my BreezeJS projects...
Gravatar
# re: An Editor Pattern for Knckout.js Using TypeScript Inheritance
Oisin Grehan
5/9/2013 3:29 PM
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.)
Gravatar
# re: An Editor Pattern for Knckout.js Using TypeScript Inheritance
Morteza
6/29/2013 5:33 AM
Good job. But have a typo in title: "knockout.js"
Gravatar
# re: An Editor Pattern for Knockout.js Using TypeScript Inheritance
Massanu
4/10/2014 7:41 PM
Do you have a fiddle working I analyzed all yoru code an tried to implement it in a real case scenario

but unable to do it

Post Comment

Title *
Name *
Email
Comment *  
 

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud