DEV Community

Discussion on: From classes to plain objects and pure functions

Collapse
smalluban profile image
Dominik Lubański Author • Edited on

I think you just put my example in the file and run it ;) Then of course fullName will not work - it is just a function that requires a host as an argument. The library is doing that when it defines properties - this example uses translation feature, so the final definition (if you pass this to define('my-element', MyElement)) will be:

const MyElement = {
  firstName: 'Dominik',
  lastName: 'Lubański',
  fullName: {
    get: ({ firstName, lastName }) => `${firstName} ${lastName}`,
  },
};

define('my-element', MyElement);

Then your custom element will have element.fullName property, which works and returns concatenated first and last name.

Collapse
basickarl profile image
Karl Morrison

I appreciate the answering, however it's still failing!

define('my-element', MyElement);
^

ReferenceError: define is not defined
    at Object.<anonymous> (/home/karl/dev/javascript/sandbox.js:10:1)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11

I'm trying to run this in Node v12

From the looks of it you are using RequireJS? How would a pure JavaScript implementation look like?

Thread Thread
smalluban profile image
Dominik Lubański Author

My code is not fully working example ;) It's a most important part of the file. You still need to import the library. If you use some kind of bundler you can use this:

import { define } from 'hybrids';
...

If you want "pure" JS solution, you can use ES modules:

<script type="module">
  import { define } from 'https://unpkg.com/hybrids@4.0.3/src';

  const MyElement = {
    firstName: 'Dominik',
    lastName: 'Lubański',
    fullName: {
      get: ({ firstName, lastName }) => `${firstName} ${lastName}`,
    },
  };

  define('my-element', MyElement);
</script>

Or for older browsers support:

<script src="https://unpkg.com/hybrids@4.0.3/dist/hybrids.js"></script>
<script>
  var define = window.hybrids.define;

  ...
</script>

Read more in Getting Started section of the library documentation.