Friday, November 09, 2012

Knockout and metaprogramming

Knockout.js is great, but you often stumble as soon as you have a JSON object - how do you stuff it into the view model?

The manual touches on it a little, but understanding what the mapping plugin is doing is quite helpful too.

The main annoyance I've had with knockout is the accessors are all methods - I'm forever assigning to the view model object as though it was a hash or these were normally properties.

The trick to remember is you can treat an object like a hash, and iterate through all of it's members, invoking them.

var foo = {

    view_model: {
      application: function () {}
    },


    map: function (data) {
      var self = this, n;

      for (n in data) {
        if (!self.view_model.application[n]) {
          self.view_model.application[n] = ko.observable();
        }

        self.view_model.application[n](data[n]);
      }
    },
    init: function (application_data) {
      varself = this;

      self.map(application_data);

      ko.applyBindings(self.view_model);
   }
};

Obviously, this doesn't handle ObservableArrays and much more - for that I would strongly recommend you use the proper mapping plugin.

However, if you:

  • Need to explore your view model
  • Need to do light weight assignment of relatively flat data
  • Or just want to get a feel for what's going on conceptually with mapping plugins
... then it's a handy technique to know.

Post a Comment