Power up your Oracle JET — Introducing our Knockout helper library

Janis Krasemann
enpit-developer-blog
2 min readJan 6, 2017
Accelerate your Oracle JET development with our open-source Knockout helper library

When your Oracle JET application grows past a certain size, chances are you define a lot of Knockout view models over the time. Unfortunately, Knockout does not offer a straightforward way of passing data to other view models. During our JET development her at enpit, we experienced that it can get quite messy when view models have to talk to each other. We overcame the challenge by building a small helper library called knockout-context-util, but more on that later.

Geertjan Wielenga describes in his blog how different view models can talk to each other using Knockout’s dataFor function:

ko.dataFor(document.getElementById('mainContent')

This basically accesses the Knockout context of the given element and returns all it’s data (which is stored in the $data attribute). This approach solves the problem, but has two annoyances:

  1. You always have to check if document.getElementById('mainContent')) really returns the desired DOM element — the dataFor function will obviously crash if you pass null or undefined as a parameter.
  2. You have to keep track of all the IDs you use for your modules. This is especially annoying if you reference your root/main view model most of the time — which is often the case in our applications.

Solution: The open-source knockout-context-util

We wrote a small library that hides all the minor annoyances of accessing the data of a view model: The knockout-context-util. It offers functions for accessing the view model of a given DOM selector, like this:

var viewModel = knockoutUtil.getViewModel('#myModelId');
// same as: ko.dataFor(document.getElementById('myModelId')).$data

This saves you the hassle of checking for errors of your document.getElementById and subsequent ko.dataFor calls — the function already does that for you.

There is also a convenience function for accessing the main view model via getRoot() — the selector of which can be configured upon instantiation. For more details about setup and usage, feel free to head over the repository on Github. If you like what we did there, install it via bower install --save knockout-context-util.

If you are interested in more content about Oracle JET, make sure to follow the enpit developer blog — we have a lot more good stuff coming within the next few months! Also, feel free to visit us on Github, Twitter or on our dedicated Oracle JET subpage.

--

--

Janis Krasemann
enpit-developer-blog

Studying computer science. Software developer at enpit consulting (mainly Javascript). Borussia Dortmund, E-Guitar, Bouldering, Programming, Tech, Gaming.