JavaScript and Knockout.js Components
RequireJS and the UI Component layer
Magento front-end JS uses RequireJS with requirejs-config.js for path and shim mapping. UI components are declared in XML (uiComponent) and backed by JS Component classes extending uiComponent or uiElement. Knockout.js provides observable data binding: observable, observableArray, computed, and ko.applyBindings. The binding context exposes $data, $parent, $root.
Component lifecycle
A UI component has initialize(), initObservable(), and default properties. defaults merges config; listens binds to events; exports exposes properties. Knockout templates use data-bind with visible, text, foreach, click, and i18n bindings. Traps: mutating an observable array without push/remove (no re-render), or reading an observable without parentheses.
Traps to expect
- Forgetting
ko.observable()requires()to read the value. - Using
$t()without the i18n binding or translator. - Assuming
requirejs-config.jsmerges by replacement rather than by config merge rules. - Breaking
x-magento-initinitialization by wrong selector or*scope.
Rule of thumb
Declare JS via x-magento-init or data-mage-init with a selector; keep component logic in uiComponent subclasses, and expose only what templates bind to via exports.
Worked example
<script type="text/x-magento-init">{ "*": { "Vendor_Module/js/counter": {} } }</script> initializes the module for every element; the module returns a function receiving config and can ko.applyBindings to a scoped element.
Checkout context
Checkout uses Magento_Checkout/js/view/* components; customizing requires understanding quote, totals, and the checkoutProvider registry.