Showing posts with label knockout. Show all posts
Showing posts with label knockout. Show all posts

Tuesday, June 21, 2016

Creating Relational Views with Oracle JET (... or Passing Parameters to Child Views)

When building composite user interfaces, how do you share data between nested views? Nested views are a key element of modular applications. I recently gave advice for determining when to use Modular Views in Knockout with Oracle JET. When breaking a user interface into reusable components, a developer has to consider the relationships between data within those user interface fragments. The WorkBetter Oracle JET Sample application is an example of a modular user experience that shares information between parent and child views. In the WorkBetter example, the sharing is between the main container "root" view and route-related views. Here is a list of ways we can share information between views:

  • Context variables such as $parent, $parents, and $root;
  • Global AMD/RequireJS modules; or
  • Parameters (knockout components or ojModule)

Context Variables ($parent, $parents, and $root)

This is a common approach because of its simplicity. If you are writing a child View and you know the structure of the parent View, then why not just reference the parent context through $parent?

I really, really don't like this option. Before I tell you why, I want to make this clear up front:

There is nothing wrong with $parent or any other context variable.

I use context variables such as $parent all the time inside a single view to reference hierarchical contexts within that same view. What I don't like is using context variables to reference a higher scope outside the current View and ViewModel. Here is why:

Referencing ancestor ViewModels from a child ViewModel creates an implicit, unwritten contract between a child ViewModel and its ancestors.

Any changes to the parent ViewModel will have an impact on the child ViewModel and there is nothing in the parent View or ViewModel alerting other developers to this relationship.

Global AMD/RequireJS Modules

This method has some merit. I use it for sharing configuration-like information, information that is common to the entire application, not view specific. The benefit of this alternative is that it is the least coupled. What makes this approach suboptimal, however, is that we are using globals to pass values when globals are not necessary. Every module has an opportunity to interact with a global variable. This approach is sort of like having a private conversation by pinning messages to a global message board knowing that anyone can read and change the message anytime.

Besides the potential for eavesdropping, I discourage this approach because it does nothing to document the contract between related ViewModels. By definition, there is a relationship, but the relationship is hidden by the use of globals. At least the Context Variables approach identified the relationship through the use of Context Variables.

When using globals in this manner, be careful with the module's exposed interface. Don't allow writing to a variable that should be read only and watch for side effects. Although effective for sharing between ViewModels, there are much better ways.

Parameters

This is my favorite option because it explicitly defines the relationship between ViewModels. The parent determines what data to share with the child view and explicitly passes that data through the params attribute. The child ViewModel explicitly identifies its params through its ViewModel constructor. Here is an example of a parent View that uses the params attribute to share data with a child ViewModel:

<div class="oj-flex oj-margin">
  <!-- ko foreach: {data: employees, as: 'emp'} -->
  <div data-bind="ojModule: { name: 'gMMqrR',
                  params: emp }">
  </div>
  <!-- /ko -->
</div>

The parent View clearly defines emp as data to share with a child ViewModel. Here is the child ViewModel:

define(['knockout'], function(ko) {
  'use strict';

  var ViewModel = function(employee) {
    var self = this;
    self.employee = employee;
  };

  ViewModel.prototype.selectEmployee =
    function(data, event) {
      console.log("You selected", data.employee.name);
    };

  return ViewModel;
});

The child ViewModel's constructor parameter clearly identifies its data requirements. Here is the codepen if you are interested in fiddling with this solution:

See the Pen Oracle JET 2.0.1 ojModule Params by Jim Marion (@jimj) on CodePen.

Here is the child ojModule codepen:

See the Pen Oracle JET 2.0.1 ojModule Params (submodule) by Jim Marion (@jimj) on CodePen.

Keeping with the best practice identified in Modular Views in Knockout and Oracle JET, I used a child module to encapsulate event handlers within a scope change. This example is rather simplistic with its small View and ViewModel, so ojModule may be overkill. Let's think about what this view would look like if I had not used a separate module. Here is the combined view:

<div class="oj-flex oj-margin">
  <!-- ko foreach: {data: employees, as: 'emp'} -->
  <div class="oj-panel oj-margin"
      data-bind="click: $parent.selectEmployee">
    <i data-bind="text: emp.name"></i>
  </div>
  <!-- /ko -->
</div>

This is not that exciting or unique really. Notice that I had to use $parent in the View. This is a perfectly acceptable use of a context variable. $parent in this scenario allows us to access an event handler method at a higher context than the current context. Now imagine a much larger scenario where you have lots of foreach constructs and related event handlers. Using ojModule to keep handlers directly related to their views within submodules may make code easier to read and comprehend.

→ BEGIN RABBIT TRAIL

The child codepen above demonstrates one more important practice: defining functions as few times as possible. The ViewModel module for the child ojModule defines the selectEmployee click handler as a prototype method rather than defining the function inside the constructor. It may be more common in knockout to use constructor defined functions as follows:

var ViewModel = function(employee) {
  var self = this;
  self.employee = employee;
  self.selectEmployee = function() {
    console.log("You selected", self.employee.name);
  };
};

The problem with this code is that it defines a new self.selectEmployee function for each employee (each iteration of the ko foreach). This would create one new instance of the function object for each element in the array. Think of the performance impact! When using embedded modules in loops, this is an important consideration. This is a key difference between child modules and standard navigational modules and something to consider when creating child modules.

Another way to write this is to use private functions. Here is the same ViewModel, but using a private function definition:

define(['knockout'], function(ko) {
  'use strict';

  var selectEmployee = function(data, event) {
    console.log("You selected", data.employee.name);
  };

  var ViewModel = function(employee) {
    var self = this;
    self.employee = employee;
    self.selectEmployee = selectEmployee;
  };

  return ViewModel;
});

Either add to the prototype or use a private function OUTSIDE the constructor. I'm not sure it matters. The important point is to minimize creating functions inside loops.

← END RABBIT TRAIL

Passing Methods to Child Modules

Within our ojModule example, let's say we want to track the selected component at the root level. How would you notify the root ViewModel that the selection changed? One way is to pass a callback (or an observable) as a parameter to the child ojModule. Here is what the new View would look like:

<div class="oj-flex oj-margin">
  <!-- ko foreach: {data: employees, as: 'emp'} -->
  <div data-bind="ojModule: { name: 'XKNNPw',
                  params: {
                      employee: emp,
                      onselect: $parent.selectEmployee
                  } }"
       class="employee">
  </div>
  <!-- /ko -->
</div>
<h2>Selected data</h2>
<pre data-bind="text: ko.toJSON(selectedEmployee, null, 2)">

Notice that I again used $parent inside my View to reference a higher scope. Just to make sure I'm clear, there is nothing wrong with using $parent to reference a higher scope within the same View. $parent only becomes problematic when referencing scopes beyond the current View.

Here is the parent/root ViewModel that defines the selectEmployee method.

  var ViewModel = function() {
    var self = this;

    self.employees = employees;

    // stores selected employee
    self.selectedEmployee = ko.observable({});

    // click handler for submodule
    self.selectEmployee = function(employee) {
      self.selectedEmployee(employee);
    };
  };

... and the child module ViewModel:

define(['knockout'], function(ko) {
  'use strict';

  var ViewModel = function(params) {
    var self = this;
    self.employee = params.employee;
    self.clickHandler = params.onselect;
  };

  return ViewModel;
});

Click an employee in the list below and watch the Selected Data region change. Hint: use the tab key to move between items and the enter or space key to select items.

See the Pen Oracle JET 2.0.2 ojModule Function Params by Jim Marion (@jimj) on CodePen.

Tuesday, June 14, 2016

Modular Views in Knockout and Oracle JET

"I have a View and ViewModel and I'm wondering if I should break it into multiple child Views and ViewModels." This is a great question and one that I've asked myself many times. Here are my criteria:

  1. Can I divide my workload, allowing others to help me if I convert sections of a view into sub views? (avoid merge conflicts)
  2. Am I using scope-changing constructs such as ko foreach?
  3. Is my ViewModel (or view) over 100 lines?

Conflict: I suppose there are people that take great pleasure in resolving merge conflicts. I'm not one of them. I can't say that I'm a fan of any type of conflict. Merge conflicts fall into that same "conflict/resolution" bucket. If I am working on a project with a teammate and we both need to access the same view, then I may give great consideration to partitioning that view.

Scope: It is quite common to use ko foreach and other scope-changing constructs. Often I find myself iterating over a data set. For each element in that data set, it is given that I will have to respond to some type of event: click to delete a row, view details, and so on. It is at this point, when I'm writing the event handler, that I realize I have changed scope. I have 3 options:

  • Put my event handler at the root of my ViewModel and reference it using context variables ($page) and then try to figure out how to identify the current element (such as ko.dataFor(event.target)),
  • Enrich my child data model with event handler methods, or
  • Move the contents of the ko foreach into a new view and ViewModel.

I'm not fond of $parent and other context-related variables. It seems too easy to lose sight of the real scope and couples my solution in a manner I'm not sure I prefer. As an alternative, I often place the content of a ko foreach in a new view and ViewModel so that event handlers and other ViewModel methods can interact with my data without scope issues. This is sort of like a scope reset.

100 lines... OK, you may have to humor me with this one. I find 100 lines to be easy to comprehend. Once I go over this threshold, code becomes more difficult to follow. I can read 100 lines with three presses of the page down key. I can keep that all in my brain and understand it without much scrolling (I suppose you could say my internal page size is 3 pages?).

Friday, May 27, 2016

Removing an Oracle JET Component from the Tab Order

A customer recently asked me if I could create a "quick entry" form that excluded certain fields from the regular tab order. Oracle JET input components have a tab index for a reason. They are designed for accessibility which means they work with accessible input devices and don't require a mouse. Removing data entry fields from the tab order means I have to use a pointing device, such as a mouse or tap, to select a skipped field. Although this goes against my better judgement, I understand the use case. If you are entering information in rapid, data entry mode, you don't want to tab over fields you rarely use. The issue I ran into is this:

How do you remove the tab index from certain Oracle JET components?

Input elements such as ojInputDate display a native HTML element and will automatically be part of the tab order. We can easily remove these elements from the tab order by setting the tabIndex to -1 like this:

<input tabindex="-1" data-bind="ojComponent: {
                    component: 'ojInputDate', value: selectedDate}" />

Other elements, such as ojSelect, use a clever collection of non-input HTML elements to capture input. For accessibility reasons, Oracle JET adds tabindex="0" to these input elements to ensure accessible devices can enter data. Since many of these Oracle JET elements begin life as a real HTML input element (input, select, etc), one might think that changing the tab index would be as easy as setting the tab index on the original input element. Unfortunately, it is not that easy. Another idea is to include tabIndex in the rootAttributes collection of an OJ component. Unfortunately, that doesn't work either. To remove these elements from the tab order, we must first identify the element with a tab index, and then change the value of the tab index. To do this effectively, we have to answer two questions:

  1. How do I identify the element with a tabIndex attribute?
  2. Timing wise, when will the DOM be ready for me to change the tabIndex?

Let's start with question #1. Study the following structure screenshot for a moment.

In the above screenshot, the JET generated oj-select is highlighted at the top. The very next element, the oj-select-choice element is the element with the tabIndex and is a child element of the oj-select. This is the element we want to modify and we need to find a way to programatically identify this element. Notice that the original select element is a sibling of the generated oj-select element. We could use a sibling selector. Sibling selectors are great for collections, where you want to style elements differently based on their position in a collection, but a sibling selector makes me a little nervous in this instance. I'm not sure we can depend on the sibling relationship identified in this screenshot. Rather than use a sibling selector, we can use Oracle JET's getNodeBySubId method. For Oracle JET components that are composed of several elements, we can identify individual pieces of the component by Sub ID. You can find the list of valid ojSelect Sub IDs here. We specifically want to select the oj-select-choice node. Unfortunately, oj-select-choice is not a node with a known Sub ID. If I expanded the oj-select-choice node in the structure screenshot, you would see that oj-select-chosen is a direct descendant of oj-select-choice. The oj-select-chosen node is selectable by Sub ID. With a little jQuery, we can easily traverse from oj-select-chosen up to oj-select-choice. We can test this by selecting our select element in the structure browser and then entering the following into the console:

$($0)
  .ojSelect( "getNodeBySubId", {'subId': 'oj-select-chosen'} )
  .closest( ".oj-select-choice" )

The following screenshot shows the results of that command (notice I also expanded the oj-select-choice to reveal the child oj-select-chosen).

A quick word about jQuery traversal methods... Using jQuery, there are often multiple ways to solve the same problem. In this situation we could either use the parents() or closest() methods to work our way up the hierarchy. Parents and Closest are similar, but, as the docs say, "The differences between the two, though subtle, are significant." We want to find the most immediate ancestor matching a selector. Closest accomplishes this. It identifies the match and then stops. The parents method, on the other hand, finds all matches and returns them as a collection. We have no need to walk the entire document hierarchy, so closest is the appropriate choice for this scenario. We have now answered question #1: How do I identify the element with a tabIndex attribute?

Next we need to handle the Life Cycle Management issue: How do we know when the ojSelect is available in the DOM (question #2)? Even though ojModule has Life Cycle Management events that tell us when the DOM is available, I don't suggest using them for this specific scenario. ojModule LCM events will work just fine with DOM elements that are hard coded into the view, but I'm not sure we should count on them for dynamically generated elements, such as those bound to an ko.observableArray. A better approach is to use a component-specific life cycle management approach such as custom bindings (ko.bindingHandlers). This allows us to manipulate an element as soon as it appears in the DOM. Here is an example ko.bindingHandler:

ko.bindingHandlers.inaccessibleOjSelect = {
  init: function(element, valueAccessor, allBindingsAccessor, ctx) {
    var options = allBindingsAccessor().ojSelectOptions || {};
    var multiple = !!options.multiple;
    var tabEl = $(element)
      // initialize ojSelect
      .ojSelect(options)
      // bind value change handler
      .on({
          'ojoptionchange': function (event, data) {
            if (data.option === "value") {
              var observable = valueAccessor();
              if (ko.isObservable(observable)) {
                if (multiple) {
                  observable(data.value);
                } else {
                  // unwrap from array if single select
                  observable(data.value[0]);
                }
              } // if not observable, just throw away the value
            }
          }
        })
      // get reference to item with tabIndex
      .ojSelect( "getNodeBySubId", {'subId': 'oj-select-chosen'})
      .closest(".oj-select-choice");

    $(tabEl).attr("tabIndex", -1);

  },
  update: function(element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    $(element).ojSelect("option", "value", [value]);
  }
};

Note: The ojSelect value expects an array. In this JavaScript, notice that I distinguish between multi and single selection modes. For single-select ojSelect elements, I am unwrapping the value array and just returning the single value. This is for convenience and is in lieu of my other method for unwrapping ojSelect values.

You would use this with HTML similar to the following:

<select id="basicSelect" data-bind="inaccessibleOjSelect: browser,
                      ojSelectOptions: {optionChange: browserChangedHandler,
                           rootAttributes: {style:'max-width:20em'}}">
  <option value="IE">Internet Explorer
  <option value="FF">Firefox
  <option value="CH">Chrome
  <option value="OP">Opera
  <option value="SA">Safari
</select>

And finally, here is the jsFiddle so you can test it out:

As you review the code, you will notice that it is very ojSelect specific. As I mentioned before, not every Oracle JET input component requires a custom handler to change the tabIndex. For those that do, however, it wouldn't take much to rework this custom handler into something generic that could be used with a variety of ojComponent elements.

Wednesday, May 18, 2016

HTML5 Input Types for Oracle JET

I read an interesting question today, "Can you use HTML5 Input Types with Oracle JET's ojInputText?" Of course, the answer is "Yes" (the answer is always Yes). A better question is "How do you use HTML5 Input Types with Oracle JET's ojInputText?" OK, before we go there, let's answer the "Why" question: "Why would you use HTML5 Input Types with Oracle JET's ojInputText?" Oracle JET already includes number, text, and date input types, all styled according to the Oracle Alta specification. The reason for HTML5 Input Types? Device support. The idea behind HTML5 input types is to allow each device to display the most appropriate input method for a specific input type. This allows mobile web apps to maintain consistency with native mobile apps. For this reason, I am a HUGE fan of HTML5 input types. Note: desktop browsers don't have very good support for HTML5 Input Types.

Let's move onto the "How" question. Can you just set the type attribute of an ojInputText to "date" and get an HTML5 date input? No. Oracle JET will reset the type attribute to "text." The trick is to register a MutationObserver to listen for changes to the type attribute, and then reset it back to date (or whatever HTML5 input type you desire). Next question: How do I assign a MutationObserver to an instance of ojInputText? At this time, the best way I know to do this is with a knockout custom binding handler. You may remember that we used a custom binding handler last time we extended ojInputText (and then reused it a few more times). The reason for registering a ko.bindingHandler is to give us life cycle management events: we know when the DOM element is available and can enhance that element as we see fit. Here is an example of a custom component named html5DateInputText that extends ojInputText through ko.bindingHandlers. On initialization, the bindingHandler configures a MutationObserver that ensures the type attribute is always date. If you don't see a browser-specific date picker in the following example, then your browser might not support the date HTML5 input type. That doesn't mean the example is broken. It still works (depending on how you define the word "works") and falls back gracefully to a plain ojInputText.

Here is the custom binding handler:

var observerConfig = {
  attributes: true,
  childList: true,
  characterData: true
};
  
// Custom binding handler that wraps ojInputText and provides extra functionality
ko.bindingHandlers.html5DateInputText = {
    // setup extension to ojInputText as well as register event handlers
    init: function(element, valueAccessor, allBindingsAccessor, ctx) {
      var options = allBindingsAccessor().ojInputTextOptions || {};
      

      var observer = new MutationObserver(function(mutations) {
        ko.utils.arrayForEach(mutations, function(mutation) {
          if (mutation.type === 'attributes') {
            if (mutation.attributeName === 'type') {
              var $target = $(mutation.target);
              if ($target.attr('type') !== 'date') {
                $target.attr('type', 'date');
              }
            }
          }
        });   
      });
        
      observer.observe(element, observerConfig);
      
      $(element)
        .ojInputText(options)
        .on({
          'ojoptionchange': function (event, data) {
            //console.log(data)
            // use option === "value" for final value
            // use option === "rawValue" for each character
            if(data.option === "rawValue") {
              var val = data.value;
              var observable = valueAccessor();
              observable(val);
            }
          }
        })

      //handle disposal (if KO removes by the template binding)
      ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        $(element).ojInputText("destroy");
        observer.disconnect();
        console.log("ojInputText destroyed");
      });
      
    },
    // This is how we update the UI based on observable changes
    update: function(element, valueAccessor) {
      var value = ko.utils.unwrapObservable(valueAccessor());
      $(element).ojInputText("option", "value", value);
    }
  };

If you want a different input type (tel, number, email and so on), then change lines 19 and 20 to match your target input type.

Note: The ojInputText Alta skin includes padding: 0 5px. The Chrome HTML5 Date spinners weren't centered using that padding so I added a line of CSS to reset padding to 5px on all sides.

Monday, May 9, 2016

rateLimit'ing ojInputText using a Read-only Observable (Debouncing the rawValue)

In my post Filtering Oracle JET ArrayTableDataSource I showed how to use an ojInputText to filter tabular data. In that post I mentioned using the knockout rateLimit extender, but shied away from it because rateLimit'ing an observable attached to an ojInputText rawValue throws the error, "rawValue option cannot be set" (even though rateLimit'ing in this manner works). It is true that rawValue is a read only field. For some reason, rateLimit'ing an observable causes a write to the component property bound to the observable. This makes sense because that is the point of an observable: update something after the observable value changes. The problem is that rawValue is read-only. I raised this issue with my colleagues and Jeanne Waldman shared this idea:

Create a pureComputed based off the rawValue observable and rateLimit the pureComputed.

Interesting. Jeanne's idea essentially creates a read-only observable that we can then rateLimit, effectively isolating rawValue from a write attempt. Here are the JavaScript changes necessary to implement Jeanne's idea:


// ... other code above here
ko.pureComputed(self.nameSearch)
  .extend({
    rateLimit: {
      timeout: 250,
      method: "notifyWhenChangesStop"
    }
  })
  .subscribe(function(newValue) {
    self.datasource.reset(
      filteredEmployees(newValue)
    );
  });

// ... other code below here

Notice that we are wrapping the previously used nameSearch observable in a ko.pureComputed, extending the ko.pureComputed, and then subscribing to the rate limited observable. Here is the jsFiddle:

Success! Our filter code now only runs 250 milliseconds after user input pauses. Considering our search algorithm, this will definitely perform better than invoking the algorithm for each key press. But is it as good as it could be? I'm not sure. We are now rate limiting a second observable rather than the primary observable. Will the primary observable continue to emit events with each key press? Did we trade an innocuous error message for some CPU/memory overhead? Does it matter? Normally, given two working solutions, I would choose performance, but I really don't want to see error messages cluttering my console.

Tuesday, April 19, 2016

Extending Oracle JET Components through Custom Bindings (Input Text with Buttons)

The other day I saw an interesting question on an Oracle JET forum: "Can you add a clear button inside the end of an ojInputText?" Think of this like the magnifying glass at the end of a search field or an X that allows you to delete all of the text within an ojInputText. My first thought was to use a little CSS to add a FontAwesome icon to the end of the data entry field. If we were using a plain HTML input element, this would be no small task because it is impossible to use CSS alone to add an icon to the end of an input element (maybe someday HTML and CSS will support before and after selectors for input elements?). ojInputText, however, already wraps input elements in an outer div so we just need to add a little CSS to style that outer div. Here is an example that just uses CSS styling

You see a problem with this solution? I didn't at first. From a visual perspective, it meets all of the requirements—oh, except it isn't a button. If all you want is a visual indicator/icon within ojInputText, then this is a small, tidy solution will suffice. If you actually wanted a button, then keep reading.

My colleague Paul Thaden reworked my example for click events:

Notice this example replaces the :after pseudo selector with jQuery append. This allows us to handle the icon's click events. This is a great, simple solution if you need to handle click events AND know when elements will exist in the DOM (so you can wire up event handlers, enhance the markup, etc). But what about those times when elements are created and destroyed through iterators or View/Component changes? What we really need is a way to manage the component's lifecycle so we can enhance and wire up event handlers on creation. Knockout has a mechanism for this called Custom Binding Handlers.

Have you noticed the $(".selector").ojFoo syntax in a lot of the Oracle JET JSDocs? That looks a lot like the jQuery UI syntax (because it is—thank you JB for confirming, see this video). If Oracle JET components are a lot like jQuery UI widgets, then we are in luck. The internet is littered with examples of people creating custom binding handlers for jQuery UI components. Here is a great example that creates a custom binding handler for the jQuery UI datepicker. All we need to do is follow that example, replacing datepicker with ojInputText. In other words, we can extend any Oracle JET component binding by pretending it doesn't have bindings and treating it like a jQuery plugin. Here is a jsFiddle showing examples of two-way data binding and data model creation/destruction, etc:

Too much clutter? Just want to see the ojInputText extension? Here is the HTML

<input id="text-input" 
       type="text"
       data-bind="audioInputText: value,
                  ojInputTextOptions: {rootAttributes:
                                        {class: 'audio-ojInputText'}}"/>

And the JavaScript

ko.bindingHandlers.audioInputText = {
    // setup extension to ojInputText as well as register event handlers
    init: function(element, valueAccessor, allBindingsAccessor, ctx) {
      var options = allBindingsAccessor().ojInputTextOptions || {};
        
      $(element)
        .ojInputText(options)
        .on({
          'ojoptionchange': function (event, data) {
            // use option === "value" for final value
            // use option === "rawValue" for each character
            if(data.option === "value") {
              var observable = valueAccessor();
              observable($(element).ojInputText("option", "value"));
            }
          }
        })
        .closest(".audio-ojInputText")
          .append('')
          .find("i")
            .click(function() {
              var msg = "This could activate the microphone... but it doesn't. " +
                "Hey, I noticed you entered '" +
                ko.utils.unwrapObservable(valueAccessor()) + "'"
              alert(msg);
            });

      //handle disposal (if KO removes by the template binding)
      ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        $(element).ojInputText("destroy");
        console.log("ojInputText destroyed");
      });
        
    },
    // This is how we update the UI based on observable changes
    update: function(element, valueAccessor) {
      var value = ko.utils.unwrapObservable(valueAccessor());
      $(element).ojInputText("option", "value", value);
    }
  };

Here is an example of an ojInputText with a delete button that deletes all of the text within the observable when clicked.

In each of the examples above, I hard coded the click handler and the icon. In prior examples, the click handler used model data, making it somewhat generic, but not generic enough to delegate clicks to the ViewModel. Let's create one final example that we'll call ojInputText Clear Buttons. This example is generic enough to use any icon library (glyphicons, fontawesome, oj icons, etc) and invokes a click handler within the ViewModel.

Wednesday, April 13, 2016

Help! I'm using Asynchronous JavaScript and my View isn't Updating

One of the most common knockout binding questions/misunderstandings I see involves updating Knockout Observables with Asynchronous data. Whether it is a select/options list, a table, a chart, or any other data-driven component, we often load data asynchronously (Ajax). The benefit of this asynchronous architecture is that our View renders before the ViewModel has all of its data. Users see most of the application render and have a feeling of better performance. It is at this render point that bindings are bound—data pointers are locked in. Now the data arrives... how you push those data values into the bound observables can be the difference between success and failure. In this blog post I want to share with you a few ways to update observables while ensuring the View stays bound to the ViewModel. First things first: we need a mock Ajax service that returns data asynchronously. In this case, mock means we aren't actually going to fetch data via Ajax. We are just going to yield JavaScript execution for a short period of time. The following listing uses setTimeout to mimic the delay of an asynchronous response:

var fakeJAX = function() {
  return new Promise(function(resolve, reject) {
    window.setTimeout(function() {
      resolve([
        {id: 101, name: "Beauregard Duke"},
        {id: 102, name: "Lucas Duke"},
        {id: 103, name: "Daisy Duke"},
        {id: 201, name: "Cooter Davenport"},
        {id: 301, name: "Jefferson Davis Hogg"},
        {id: 302, name: "Lulu Coltrane Hogg"},
        {id: 401, name: "Rosco P Coltrane"}
      ]);
    }, 2000);
  });
};

As you can see, the method returns an HTML5 Promise that resolves when the timer expires (2 seconds). The result/interface is designed to mimic the fetch API.

When it comes to out-right errors, here is the common one I see:

var ViewModel = function() {
  var self = this;

  self.employees = ko.observableArray([]);

  self.datasource = new oj.ArrayTableDataSource(
    self.employees, {
      idAttribute: 'id'
    });
      
  // Array Push All option
  fakeJAX()
    .then(function(data) {
        self.employees = ko.observableArray(data);
      });
  };

Do you see the problem? Inside the Asynchronous response handler, we are changing the self.employees pointer. This breaks the relationship between our ViewModel and the DOM. The view now points to the old memory space whereas self.employees points to a new memory space. Note: Later you will see how to work around this by using the if binding.

Now let's look at an example that is technically correct, but may not work with certain components because of the internal workings of the component (the way the component is implemented and how it binds to the observable). In Knockout it is common to swap out the value of the observable. This works great... most of the time. Here is an example:

fakeJAX()
  .then(function(data) {
    self.employees(data);
  });

Now don't get me wrong. This works most of the time. But if you find that your observable isn't updating, then try pushing values directly into the array wrapped by the Observable Array. Here is an example:

fakeJAX()
  .then(function(data) {
    ko.utils.arrayPushAll(self.employees(), data);
    self.employees.valueHasMutated();
  });

There are times where pushing into the array in-place won't work either. If you find yourself in a situation where the last two options won't work, then try this next approach. I have yet to find a scenario where this next approach does not work. It uses the knockout if binding to hide a data bound element from the DOM until we have data. Here is an HTML example of a table wrapped in an if binding:

<!-- ko if: haveEmployees --> 
  <table id="table" summary="Employee Table 2" aria-label="Employee Table"
         data-bind="ojComponent: {component: 'ojTable',
                    data: datasource,
                    columnsDefault: {sortable: 'none'},
                    columns: [{headerText: 'Employee Id',
                    field: 'id'},
                    {headerText: 'Employee Name',
                    field: 'name'}]}">
  </table>
<!-- /ko -->  

Notice the haveEmployees ViewModel observable? There are a couple of ways to implement that observable, but my favorite way is through a knockout pureComputed like this:

self.haveEmployees = ko.pureComputed(function() {
  return (self.employees().length > 0);
});

Now when the fakeJAX success handler populates the observableArray, the hasEmployees pureComputed will automatically flip from false to true and the table will suddenly appear in the DOM. It is at this moment that knockout will bind observables to attributes. Since binding happens after we have data, this may seem like the easiest approach. In my opinion, however, this should be the last option chosen because it hides a portion of the user interface until the Ajax response.

I put together a jsFiddle showing the last two approaches named Async Data Binding.

Interested in learning more? Here are a couple of Oracle JET OTN Discussion Forum threads discussing this very topic:

Special thank you to @JB, Oracle JET product manager for chiming in on those threads

Thursday, March 24, 2016

Filtering Oracle JET ArrayTableDataSource

I recently wrote about Filtering Table Data with Knockout Computeds. I'm not sure I shared anything earth shattering as others have already written about that topic. My real motivation for writing that post was to provide a foundation to compare/contrast filtering a plain HTML table against an Oracle JET ojTable that is based on an oj.ArrayTableDataSource (not to be confused with oj.CollectionTableDataSource, which wraps an oj.Collection and has its own where method and cookbook example).

Let's jettify the Filtering Table Data with Knockout Computeds example. Instead of <input type="text">, we'll use ojInputText. Instead of a Bootstrap table, we'll use ojTable. Here is the jsFiddle:

As you can see, the code is fairly similar. A couple of key differences to note are the rawValue parameter and the lack of a computed. Instead of using the value and valueUpdate parameters, the ojInputText component uses value and rawValue. The ojInputText value parameter acts just like the standard knockout parameter, tracking the final updated value after losing focus. The rawValue parameter tracks changes as you type, which is similar to the standard input with the valueUpdate parameter. The other difference between these examples is that this example didn't use a computed observable, but rather the oj.ArrayTableDataSource.reset() method to replace the table's array when filtering.

As with the Knockout computed example, we can debounce this example so that the array filter code doesn't run with every key press, but only after a predetermined pause. I included the rate limiting extension in the JavaScript, but commented it out for example purposes. When filtering large data sets, it might make sense to switch from observing rawValue to observing the value parameter. Another option is to include a Search button that triggers the filter code on click. You can find an example of this here.

Note: Filtering arrays requires an ES6 compatible browser or some type of polyfill library. The examples include Lazy.js as a polyfill so you can run the jsFiddle example in a wider range of web browsers.

Wednesday, March 23, 2016

Filtering Table Data with Knockout Computeds

Before learning to love Knockout, I was an AngularJS fan. AngularJS has this really cool feature called filters that let you pipe a collection through a filter, filtering results based on the value of a field. The AngularJS filter page has a great inline example. You can filter with Knockout, but it isn't quite as simple. The key to filtering in Knockout is the computed observable. I put together an example:

This example contains a search field in the upper right corner as well as a table of employee names. If the filter field is empty, then the table should display all employees. If the filter field contains a value, then the table should display only employees with names containing the search value. When you look at the JavaScript for this example, you will see:

  1. An array of employees (the raw, unobserved data),
  2. An observable for the search value, and
  3. A computed for the filtered table

Drilling into the computed observable (filteredEmployees), we see that the function immediately returns the list of all employees if the nameSearch observable has no value. If it has a value, then it returns a filtered array of matching results.

I put together 2 examples: One with ES6 Array and String extensions and a Lazy.js version. The example above is the Lazy.js version. ES6 is great, but jsPerf tests show better results for ko.utils, underscore, Lazy.js, or just about any other non-native library. I also hesitate to use the ES6 Array.prototype.filter for browser compatibility reasons. Just in case you are interested, Here is the ES6 version. Why Lazy.js instead of just ko.utils.arrayFilter? I am a big fan of Lazy.js's function composition rather than the traditional chained intermediate array concept (even though this example doesn't exactly chain enough array methods together to see a performance improvement from Lazy.js).

On the HTML View side, the search field's data-bind attribute uses the valueUpdate parameter. This causes Knockout to update the ViewModel on some other event besides the change event. That way users can see changes as they type. What this means is as you type, the filter code will run, filtering the results displayed in the table. We have a small data set, so you won't notice, but on a larger data set, this could have serious performance implications because each key press would iterate over the Employees array. We can limit how often knockout recomputes the computed observable by debouncing, or rate limiting, updates of nameSearch field like this:

self.nameSearch.extend({
    rateLimit: {
      timeout: 500,
      method: "notifyWhenChangesStop"
    }
  });

You can see an example here. Notice that the update is a little choppier, meaning the table filters a half second after you stop typing. A half second may be a little too long between updates. The important part is that the code recalculates the computed AFTER the specified event pauses for a predetermined interval.