Skip to content

Commit

Permalink
feat(bind): events and getters have 'this' bound to the target element
Browse files Browse the repository at this point in the history
  • Loading branch information
MrAntix committed Jan 19, 2019
1 parent 6f44951 commit 875b876
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
},
"jest": {
"preset": "ts-jest",
"verbose": true,
"verbose": false,
"testMatch": [
"**/*.spec.ts"
],
Expand Down
40 changes: 39 additions & 1 deletion src/bind.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,44 @@ describe('bind', () => {
const el = document.querySelector<HTMLElement>('[bind]');
await el.click();

expect(recievedEvent).not.toBeNull();
expect(recievedEvent).not.toBeUndefined();
});

it('this is bound to element in getters', async () => {
document.documentElement.innerHTML = '<div bind [inner-html]="html"></div>';

const el = document.querySelector<HTMLElement>('[bind]');
let elThis: HTMLElement;

const context = {
get html() {
elThis = this;
return '<span>inserted</span>';
}
};

bind(document, context);

expect(el.innerHTML).toEqual(context.html);
expect(elThis).toBe(el);
});

it('this is bound to element in event handlers', async () => {
document.documentElement.innerHTML = '<div bind {click}="onClick"></div>';

const el = document.querySelector<HTMLElement>('[bind]');
let elThis: HTMLElement;

const context = {
onClick: function() {
elThis = this;
}
};

bind(document, context);

await el.click();

expect(elThis).toBe(el);
});
});
4 changes: 2 additions & 2 deletions src/bind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function bind(rootElement: Document | Element, context: any): void {
}
if (getValue() !== value) setValue(value);
},
get: getValue
get: getValue.bind(element)
});
component[binding.componentMemberName] =
context[binding.contextMemberName];
Expand All @@ -43,7 +43,7 @@ export function bind(rootElement: Document | Element, context: any): void {
getBindings(eventsExp, element, attributeNames).forEach(binding => {
element.addEventListener(
binding.componentMemberName,
context[binding.contextMemberName]
context[binding.contextMemberName].bind(element)
);
});
});
Expand Down

0 comments on commit 875b876

Please sign in to comment.