Skip to content

Calling .unbind() from within a callback skips next callback #10

@aron

Description

@aron

Because .trigger() is iterating over the array of callbacks when a callback unbinds itself .splice() modifies the array and the it's length decreases by one so the next callback in line is skipped.

In the following example we unbind function B in it's own callback. We would expect "ABC" to be output but instead we only get "AB".

var e = new MicroEvent();

e.bind('change', function A() { console.log('A'); });
e.bind('change', function B() { console.log('B'); e.unbind('change', B); });
e.bind('change', function C() { console.log('C'); });

e.trigger('change'); //=> Expect A B C, but C is not called.

There are at least two solutions, clone the array in either the .trigger() or .unbind() methods. [].slice() will do this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions