Skip to content

Template convention

Anders Malmgren edited this page Nov 3, 2015 · 12 revisions

Any type of object or array of items where the item satisfy the condition

typeof === "object" //Excluding strings, booleans, numbers, etc

Can be bound to a arbitrary element but the element in question must not contain children. By convention the library will look for a template with the same name as the ViewModel minus the postfix 'Model'. A model named CustomerViewModel will be binded to a template named CustomerView.

<div data-name="subView"></div>

<script id="SubTestView" type="text/html">
   <span data-name="value"></span>
</script>

http://jsfiddle.net/xJL7u/11/

Note

Javascript is a dynamic language so to find the type name of a ViewModel the library has to iterate the entire window object to find your constructor and then match that to the member of the parent. To make this process faster and more secure always specify your object root (Namespace). This way the library only needs to iterate your applications object tree.

ko.bindingConventions.init({ roots: [MyApp] });

The type name finder should be able to find most kinds of JS Objects. But there are a few pitfalls that you need to know.

  • If you use prototype declared ViewModels be sure not to overwrite the constructor on the prototype object, correct syntax:
MyApp.MyViewModel = function() {
};
MyApp.MyViewModel.prototype = {
   constructor: MyApp.MyViewModel,
   save: function() {
   }
};
  • The type finder finds the correct type by comparing the constructor on your instance with the constructors it finds while iterating your object tree. If you are using a OO framework make sure it's not overwriting the constructor. myViewModelInstace.constructor === MyApp.MyViewModel.constructor must return true for the type finder to work.

  • The type finder tries first to parse the constructors name using the ToString result. Some OO frameworks returns it's own name here "Class" etc, you need to tell the type finder about these special cases. By default "Class" is exluded form the type finder. If you use a OO library that uses a different name add it to the options by doing

ko.bindingConventions.init({ roots: [MyApp], excludeConstructorNames: ["Class"] });

Override view locator

We have added the possibility to override the view locator from version 1.5.114 of the library. Its done like

ko.bindingConventions.viewLocator.instance = {
   init: function() {
      //Optional init method, not required. Its called when library is initilized (When ko.applyBinding is called)
   },
   getView: function(viewModel) {
      //Custom logic to get view name
     return "DummyView";
   }
};