Skip to content
Myr

feat: `this` in recipe is no longer the draft, but unbound

Before adoption: this commit came in with the history the project adopted, so no landing records it.

BREAKING CHANGE

authored by Michel Weststrate · committed by Alec Larson · parent 9077851 · Browse files · 3 files+22 added−28 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+22 added−28 removed

  • tests:+17 added−25 removed
  • other:+5 added−3 removed

3 files+22 added−28 removed

modified:__tests__/base.js+17 added-10 removed
769 unmodified lines
770 expect(Reflect.has(draft.anArray, "17")).toBe(false)771 })772 })773774 it("'this' should work - 1", () => {774 it("'this' should not be bound anymore - 1", () => {775 const base = {x: 3}776 const next1 = produce(base, function() {777 this.x = 4777 expect(this).toBe(undefined)778 })779 expect(next1).not.toBe(base)780 expect(next1.x).toBe(4)779 })780783 it("'this' should work - 2", () => {784 const base = {x: 3}781 it("'this' should not be bound anymore - 2", () => {782 const incrementor = produce(function() {786 this.x = 4783 expect(this).toBe(undefined)784 })788 const next1 = incrementor(base)789 expect(next1).not.toBe(base)790 expect(next1.x).toBe(4)785 incrementor()786 })787788 it("it should be possible to use dynamic bound this", () => {789 const world = {790 counter: {count: 1},791 inc: produce(function(draft) {792 expect(this).toBe(world)793 draft.counter.count = this.counter.count + 1794 })795 }796797 expect(world.inc(world).counter.count).toBe(2)798 })799800 // See here: https://github.com/mweststrate/immer/issues/89801 it("supports the spread operator", () => {802 const base = {foo: {x: 0, y: 0}, bar: [0, 0]}803 const result = produce(base, draft => {
471 unmodified lines
modified:__tests__/readme.js-15 removed
modified:src/immer.js+5 added-3 removed
37 unmodified lines
38 // curried invocation39 if (typeof base === "function" && typeof recipe !== "function") {40 const defaultBase = recipe41 recipe = base42 const self = this4344 // prettier-ignore44 return (base = defaultBase, ...args) =>45 this.produce(base, draft => recipe.call(draft, draft, ...args))45 return function curriedProduce(base = defaultBase, ...args) {46 return self.produce(base, draft => recipe.call(this, draft, ...args))47 }48 }4950 // prettier-ignore51 {
12 unmodified lines
64 const scope = ImmerScope.enter()65 const proxy = this.createProxy(base)66 let hasError = true67 try {66 result = recipe.call(proxy, proxy)68 result = recipe(proxy)69 hasError = false70 } finally {71 // finally instead of catch + rethrow better preserves original stack72 if (hasError) scope.revoke()
217 unmodified lines