I have a uiComponent defined

    ['jquery', 'ko', 'uiComponent', 'Magento_Ui/js/modal/modal', 'domReady!'],
    function($, ko, Component, modal) {
        'use strict';

        return Component.extend({
            initialize: function() {

                //get view model here   

I have a couple of questions:

1. Is the Magento2 uiComponent a knockout component ?

2. Does this basic component has a view model created and attached to it on Component.extend ?

3. If the view model does not exist how do we add it to the component (better to have it in writing if that is the case) ?

4. How can I get the component view model in the initialize method ?

  1. Yes.

  2. The js code you posted is the component view model, the component also needs a template. In your view model we can add any logic or data to be used in the template. For example, let's add an observable:

    return Component.extend({
        value: ko.observable('Hello world'),
        initialize: function() {
  3. As stated, your view model already exists but you need to create your component template. This is a simple html file which can use knockout methods and any logic defined in your view model:

<span data-bind="text: value"></span>

To initialize your component (view model and template) you can do so in a phtml file:

<script type="text/x-magento-init">
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "example-scope": {
                    "component": ”Vendor_Module/js/example-view”,
                    "template": "Vendor_Module/template/example-template”
<div data-bind="scope: 'example-scope'">
    <!-- ko template: getTemplate() --><!-- /ko -->

Which will render your your component:

<span>Hello world</span>

Components can also be initialized in xml, see for example Magento_Checkout/view/frontend/layout/checkout_index_index.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.