Showing posts with label bindings. Show all posts
Showing posts with label bindings. Show all posts

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.

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