Magento 2 – Accessing a JS UI Component’s Members from Another JS Module

javascriptmagento2uicomponent

I take it we're all accustomed with the omnipresent

// js-module1.js
define(
    ['Magento_Module/js/someComponent'],
    function (Component) {
        return Component.extend({property: 123});
    }
);

But how can you access members (properties, methods) of the Component in another JS module (public access I mean)? For example, another js-module2.js requiring the first one:

// js-module2.js
define(

    ['Magento_Module/js/js-module1'],

    function (Component) {
        var prop = Component.property; 
        // expecting "123", but it's an error, as Component is a function
    }
);

From what I understand, the returned value is actually this one here, as that's the base "class" of the JS Component, but that code is so confusing right now.

What is that thing? Can its members be accessed publicly? Some of the native view models have really nice properties/methods which could help me, but I can't get to them.

Best Answer

I'm completely sure this is not the way it is desiged to be used, but in module2 you can just do

// does not work
var prop = Component.property; 

// works!
var prop = Component.call().property; 

With the call() you return the very same instance:

// js-module1.js

var myGlobalTest;

define(
  ['Magento_Module/js/someComponent'],
  function (Component) {
    myGlobalTest = this;
    return Component.extend({});
}
);

.

// js-module2.js

define(
    ['Magento_Module/js/js-module1'],

    function (componentToUse) {
        myGlobalTest === componentToUse.call()  // true
    }
);