Skip to content

Commit

Permalink
fix(core): allow user set new value
Browse files Browse the repository at this point in the history
closes #58
closes #42
closes #29
  • Loading branch information
acrazing authored and stevemao committed Jul 1, 2017
1 parent 421cfc5 commit 98968ee
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 5 deletions.
56 changes: 54 additions & 2 deletions src/__tests__/autobind-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ describe('autobind method decorator', function() {
}, /@autobind decorator can only be applied to methods/);
});


it('should not override binded instance method, while calling super method with the same name', function() { // eslint-disable-line max-len
it('should not override bound instance method, while calling super method with the same name', function() { // eslint-disable-line max-len
class B extends A {

@autobind
Expand Down Expand Up @@ -210,3 +209,56 @@ describe('autobind class decorator', function() {
});
});
});

describe('set new value', function() {
class A {
constructor() {
this.data = 'A';
this.foo = 'foo';
this.bar = 'bar';
}

@autobind
noop() {
return this.data;
}
}

const a = new A();

it('should not throw when reassigning to an object', function () {
a.noop = {
foo: 'bar'
};
assert.deepEqual(a.noop, {
foo: 'bar'
});
assert.equal(a.noop, a.noop);
});

it('should not throw when reassigning to a function', function() {
a.noop = function noop () {
return this.foo;
};
assert.equal(a.noop(), 'foo');
const noop = a.noop;
assert.equal(noop(), 'foo');
assert.equal(a.noop, a.noop);
});

it('should not throw when reassigning to a function again', function() {
a.noop = function noop2 () {
return this.bar;
};
assert(a.noop(), 'bar');
const noop2 = a.noop;
assert.equal(noop2(), 'bar');
assert.equal(a.noop, a.noop);
});

it('should not throw when reassigning to an object after bound a function', function() {
a.noop = {};
assert.deepEqual(a.noop, {});
assert.equal(a.noop, a.noop);
});
});
15 changes: 12 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,28 @@ function boundMethod(target, key, descriptor) {
return {
configurable: true,
get() {
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
if (definingProperty || this === target.prototype || this.hasOwnProperty(key)
|| typeof fn !== 'function') {
return fn;
}

let boundFn = fn.bind(this);
definingProperty = true;
Object.defineProperty(this, key, {
value: boundFn,
configurable: true,
writable: true
get() {
return boundFn;
},
set(value) {
fn = value;
delete this[key];
}
});
definingProperty = false;
return boundFn;
},
set(value) {
fn = value;
}
};
}

0 comments on commit 98968ee

Please sign in to comment.