Skip to content

Template convention

AndersMalmgren edited this page Dec 21, 2012 · 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 'ViewModel'. 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/

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 appslications object tree.

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

The type name finder should be able to find most kinds of JS Objects, 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 frame work make sure it not overwriting the constructor, this library is for example tested with the Simple Javascript Inheritance and that library is overwriting the constructor to support OO and it breaks the type finder. In next release you will be able to supply a constructor comparer so that you can write your own logic to compare constructors.

Clone this wiki locally