Skip to content
This repository has been archived by the owner on Feb 8, 2019. It is now read-only.

Not working bind function #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
29 changes: 28 additions & 1 deletion addon/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { decorator } from '@ember-decorators/utils/decorator-wrappers';
import extractValue from '@ember-decorators/utils/extract-value';
import { run } from '@ember/runloop';

function decoratorWithReturnValue(fn) {
Expand Down Expand Up @@ -28,4 +29,30 @@ function decoratorWithReturnValue(fn) {
* ```
* @function
*/
export const next = decoratorWithReturnValue(run.next);
export const next = decoratorWithReturnValue(run.next);

/**
* Decorator that makes the target function runloop aware and binds
* it to the existing context
*
* ```js
* import Component from '@ember/component';
* import { bind } from 'ember-decorators/runloop';
*
* export default class ActionDemoComponent extends Component {
* @bind
* foo() {
* // do something
* }
* }
* ```
* @function
*/
export const bind = decorator(function(target, key, desc/*, params*/) {
const value = extractValue(desc);
// the value of `this` when the function runs is not the instance but rather the context
// of the initializer function (this === {enumerable: true, configurable: false, writable: true, initializer: ƒ})
// see this issue: https://github.com/babel/babel/issues/6977
// https://github.com/tc39/proposal-class-fields/issues/62
return run.bind(target, value);
});
26 changes: 25 additions & 1 deletion tests/unit/runloop-test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { next } from '@ember-decorators/runloop';
import { next, bind } from '@ember-decorators/runloop';
import { module, test } from 'qunit';

module('computed properties');
Expand Down Expand Up @@ -37,4 +37,28 @@ test('"run.next" works with arguments', function(assert) {
obj.nextMe('wat');
done();
}, 20);
});

test('"run.bind" works with es6 class', function(assert) {
assert.expect(1);

class Foo {
constructor() {
this.prop = 'foo';
}

@bind nextMe = () => {
return this.prop;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If you put a debugger here, the context of this is the getter {enumerable: true, configurable: false, writable: true, initializer: ƒ}

};
}

class Bar extends Foo {
constructor() {
super();
this.prop = 'bar';
}
}

let obj = new Bar();
assert.equal(obj.nextMe(), 'foo');
});