Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can.debounce keeps the context after being called the first time #782

Closed
colinexl opened this issue Mar 12, 2014 · 4 comments · Fixed by #1073
Closed

can.debounce keeps the context after being called the first time #782

colinexl opened this issue Mar 12, 2014 · 4 comments · Fixed by #1073
Labels
Milestone

Comments

@colinexl
Copy link

Hello,

We believe there is a bug in the way can.debounce works:

function (fn, time, context) {
  var timeout;
  return function () {
    var args = arguments;
    context = context || this; // buggy line, can be fixed by using var myContext = context || this
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn.apply(context, args);
    }, time);
  };
}

The context is saved in the returned function's closure so that all future calls to the debounce will get the saved context.

We discovered this bug when using can.debounce to create a event handler function for a can.Component. Once the can.Component is destroyed and reinitialized, the old (destroyed) can.Component's context is used in the can.debounce function.

I can create a JSFiddle if required but this is pretty easy to reproduce.

Thanks,
Colin Zhu

@daffl daffl added the Bug label Mar 19, 2014
@daffl daffl added this to the 2.1.0 milestone Mar 19, 2014
@daffl
Copy link
Contributor

daffl commented Mar 19, 2014

Makes sense. The easiest way would probably be to change it to:

function (fn, time, context) {
  var timeout;
  return function () {
    var args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(can.proxy(function () {
      fn.apply(this, args);
    }, context || this), time);
  };
}

@colinexl
Copy link
Author

Yep I think that will solve the issue.

@justinbmeyer
Copy link
Contributor

@daffl or @colinexl anyway one of you can get a pull request / test in by tomorrow? Otherwise, we might save this fix for 2.1.1.

@justinbmeyer justinbmeyer modified the milestones: 2.2.0, 2.1.0, 2.1.1 May 3, 2014
@ccummings
Copy link
Contributor

@colinexl Can you include your use case in this thread

@ccummings ccummings modified the milestones: 2.1.2, 2.1.1 May 22, 2014
daffl added a commit that referenced this issue Jun 11, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants