Skip to content

Supporting KnockoutJS

Henrik Vendelbo edited this page Apr 30, 2014 · 3 revisions

Declare an enhance handler

First implement the handler.

function enhance_knockout(el,role,config,context)
{
	if (window.ko === undefined) return false;
    var template = Resolver("page::templates","null")([config.contentTemplate]);
	var modelClass = global(config.model,"undefined");
	if (template && modelClass) {
		var content = template.content.cloneNode(true);
		el.appendChild(content);

		var model = new modelClass(config,context);
		ko.applyBindings(model,el);
            if (model.setContext) model.setContext(context);
		return model;
	}
	return false;
}

Then declare it,

Resolver("page").declare("handlers.enhance.knockout", enhance_knockout);

An element can now be enhanced specifying model and contentTemplate.

<div role="knockout" data-role="'model':'MyModel','contentTemplate':'#my-template'">
</div>

This will instantiate the constructor MyModel and put the #my-template in the element, and apply the bindings to the HTML.

Other handlers

You can add extra behavior for resizing and cleanup if you like.

function layout_knockout(el,layout,instance) 
{
}

function discard_knockout(el,role,instance)
{
}

Resolver("page").declare("handlers.layout.knockout", layout_knockout);
Resolver("page").declare("handlers.discard.knockout", discard_knockout);

The handlers will be moved to the Document Resolver in the near future.

Enable the role

Make sure knockout is listed in the meta tag.

<meta content="knockout" name="enhanced roles">

Clone this wiki locally