Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bind this context to owner #132

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions addon/initializers/install-function-helper-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
// typed-ember doesn't have types for `@ember/helper` yet
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { capabilities as helperCapabilities, setHelperManager } from '@ember/helper';
import {
capabilities as helperCapabilities,
setHelperManager,
} from '@ember/helper';

import type { Arguments } from '../-private/local-glimmer-interfaces-types';

Expand All @@ -18,6 +21,8 @@ export default {
initialize,
};

type Owner = unknown;

type FnArgs<Args extends Arguments = Arguments> =
| [...Args['positional'], Args['named']]
| [...Args['positional']];
Expand All @@ -36,6 +41,8 @@ export class FunctionHelperManager {
hasScheduledEffect: false,
});

owner?: Owner = undefined;

createHelper(fn: AnyFunction, args: Arguments): State {
return { fn, args };
}
Expand All @@ -44,10 +51,10 @@ export class FunctionHelperManager {
if (Object.keys(args.named).length > 0) {
let argsForFn: FnArgs<Arguments> = [...args.positional, args.named];

return fn(...argsForFn);
return fn.apply(this.owner, argsForFn);
}

return fn(...args.positional);
return fn.apply(this.owner, args.positional);
}

getDebugName(fn: AnyFunction): string {
Expand All @@ -61,4 +68,10 @@ export class FunctionHelperManager {

const FUNCTIONAL_HELPER_MANAGER = new FunctionHelperManager();

setHelperManager(() => FUNCTIONAL_HELPER_MANAGER, Function.prototype);
setHelperManager(
(owner: Owner) =>
Object.create(FUNCTIONAL_HELPER_MANAGER, {
owner: { value: owner, writable: false, configurable: false },
}),
Function.prototype
);
35 changes: 35 additions & 0 deletions tests/rendering/functions-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import { hbs } from 'ember-cli-htmlbars';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';

interface Owner {
lookup(
key: string,
options?: {
singleton?: boolean | undefined;
instantiate?: boolean | undefined;
}
): unknown;
}

module('function helpers', function (hooks) {
setupRenderingTest(hooks);

Expand Down Expand Up @@ -100,4 +110,29 @@ module('function helpers', function (hooks) {
'x is 4, and opts.a is 6',
]);
});

test('the owner is bound as `this` context', async function (assert) {
function lookup(
this: Owner,
identifier: string,
options?: object
): unknown {
return this.lookup(identifier, options);
}

const testIdentifier = 'test-value:foo';
const testValue = 'foo';

this.owner.register(
testIdentifier,
{ string: testValue },
{ instantiate: false }
);

this.setProperties({ lookup, testIdentifier });

await render(hbs`{{get (this.lookup this.testIdentifier) "string"}}`);
Copy link
Collaborator

@NullVoxPopuli NullVoxPopuli Aug 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the intent is solid, but ultimately we need the VM to see property.path (when used in the invocation position), to do path.apply(property, args)

this way we get correctly bound functions on all objects.

like, XState interpreters, window globals, services, etc

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep! I've touched on that in my most recent comment in the RFC: emberjs/rfcs#756 (comment)

I also suggested not using the owner, but the invoking template context. I'd be very interested in your opinion on that.

Copy link
Collaborator

@NullVoxPopuli NullVoxPopuli Aug 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, that would make sense to me.

the owner shouldn't get any special treatment with functions, but your functions should have whatever this you expect them to have.

so if your function needs the owner, you getOwner(this) in it.
but if your function is not defined in a place where this has an owner`, you won't get an owner.

function outerFunction() {
  getOwner(this); 
}

class extends Component {
  // can access owner
  myFunction = () => {
    let owner = getOwner(this);
  }
  
  outerFunction = outerFunction; // no owner
  boundOuterFunction = outerFunction.bind(this); // has owner
}


assert.dom().hasText(testValue);
});
});