UNPKG

@enact/core

Version:

Enact is an open source JavaScript framework containing everything you need to create a fast, scalable mobile or web application.

48 lines (47 loc) 1.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; exports.useClass = useClass; var _react = require("react"); function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /** * Creates one instance of the class, `Ctor` with the provided `args`, for the life of the * component. * * ``` * class MyClass { * constructor ({value}) { * this.value = value; * } * * handleEvent = (ev) => { * if (ev.key === 'Enter') { * // do something with this.value * } * } * } * * function Component (props) { * const inst = useClass(MyClass, props.value); * return <div onClick={inst.handleEvent} /> * } * ``` * * @param {Function} Ctor Class constructor * @param {...any} args Arguments to pass to the constructor * @returns {Object} An instance of `Ctor` * @private */ function useClass(Ctor) { var ref = (0, _react.useRef)(null); for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } ref.current = ref.current || _construct(Ctor, args); return ref.current; } var _default = exports["default"] = useClass;