Elements can include JavaScript if so required. As with widgets, JavaScript for an element should be created as an anonymous Require.js module using the format shown in the code example below. The module must be named element.js and saved in the <element-name>/js/ directory for the associated element. Within the module, you must create a variable called elementName and set that variable to the name of the element. For example, if the element files are added via an extension in <extension-name>/element/my-element, the value of elementName needs to be my-element. After these requirements are met, you can add whatever functionality your element requires to the module.

define(
  ['jquery', 'knockout', pubsub'],

  function($, ko, pubsub) {
          "use strict";

     return {
      elementName: 'my-element',
      };
    }
);

Note: See http://requirejs.org/docs/api.HTML#defdep for more details on Require.js modules.

When a widget is loaded, the JavaScript for its elements gets added to the widget’s view model. The element template is still loaded at the widget’s view model scope and the element JavaScript is available via:

$data.elements['<elementName>']

It is a good practice to check for the element JavaScript before attempting to use it. This can be done in the element’s template:

<!-- ko if: initialized() && $data.hasOwnProperty('<elementName>') -->
     [Element template code]
<!-- /ko -->

Note that without the initialized() && condition, the JavaScript loads correctly but the template code within the block is not displayed. This is because the widget template has been rendered and the if statement already evaluated to false by the time the element JavaScript loads. The check on the widget’s initialized observable ensures that the if statement will be re-evaluated when the value of initialized changes from false to true.

onLoad()

To run custom logic when the element is instantiated, add an onLoad function to the element JavaScript’s return object:

onLoad: function(widget) {
  //onLoad code here.
}

The onLoad function runs once the element has finished loading and is populated with the necessary data. This is the main access point to configure data for the element after its properties have been loaded and the system is ready to display the element. As the onLoad() function is only called the first time the element is instantiated, when returning to the same “page,” the element does not need to be re-instantiated and so onLoad() is not called again.


Copyright © 1997, 2016 Oracle and/or its affiliates. All rights reserved. Legal Notices