3

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.

  • I've not done a lot with Require so take what I say with a pinch of salt, but I think the whole point of Require is to prevent JS from being global/public. – Ben Crook Mar 9 '17 at 17:40
  • This may help - stackoverflow.com/questions/29668293/… – Ben Crook Mar 9 '17 at 17:42
  • 1
    It wasn't obvious to me at first. Namely, I thought that, if I have a public property on an exported module, I'm explicitly giving public access to said property. But your link helped me understand that it's wrapped in a function to avoid context pollution. Thanks. That helped. – nevvermind Mar 9 '17 at 22:09
2

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
    }
);
  • I'm a Require-JS noob. You've convinced me. Ben Crook, too. Thanks. – nevvermind Mar 9 '17 at 22:05

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.