Skip to content
Open
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
40 changes: 29 additions & 11 deletions __tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,28 +59,46 @@ describe('@bind', function () {
});

describe('when used to bind to this context', function () {
it('binds decorated method to this context', function () {
class thisContext {
private test: string;
class thisContext {
protected test: string;

public constructor() { }
public constructor() { }

public getTest(): string {
return this.test;
}
public getTest(): string {
return this.test;
}

@bind
public setTest(test: string): void {
this.test = test;
}
@bind
public setTest(test: string): void {
this.test = test;
}
}

it('binds decorated method to this context', function () {
const tested: thisContext = new thisContext();
const { setTest } = tested;
setTest('unit');

expect(tested.getTest()).toBe('unit');
});


it('can be overwritten as well', function () {
class thisInheritedContext extends thisContext {
@bind
public setTest(inherited: string): void {
this.test = 'inherited ' + inherited;
}
}

const tested: thisContext = new thisContext();
tested.setTest('unit');
expect(tested.getTest()).toBe('unit');

const inheritedTested: thisInheritedContext = new thisInheritedContext();
inheritedTested.setTest('unit');
expect(inheritedTested.getTest()).toBe('inherited unit');
});
});

describe('when used to bind to static context', function () {
Expand Down
13 changes: 12 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
export function bind<T extends Function>(target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void {
export function bind<T extends Function>(
target: object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
if(!descriptor || (typeof descriptor.value !== 'function')) {
throw new TypeError(`Only methods can be decorated with @bind. <${propertyKey}> is not a method!`);
}

return {
configurable: true,
set(value) {
Object.defineProperty(this, propertyKey, {
value: value,
configurable: true,
writable: true
});
},
get(this: T): T {
const bound: T = descriptor.value!.bind(this);
// Credits to https://github.com/andreypopp/autobind-decorator for memoizing the result of bind against a symbol on the instance.
Expand Down