Skip to content

Feature idea: onlyOnce method #11

Open
@dhritzkiv

Description

I recently ran into a small but confusing bug in my app while using ampersand-events (or rather, one of its dependents). I was using the once method to listen to two event names with one callback, expecting it to work like this:

var count = 0;
model.once("error success", function() {
    //I assumed, incorrectly, that this callback would fire only once, ever.
    count++;
});
model.trigger("error");
model.trigger("success");
assert.equal(count, 1); // nope. count actually equals `2`

see live example on TonicDev

But I misunderstood the functionality. There were rare cases where both success and error events could happen while those listeners were in place causing unexpected results based on the callback being called multiple times.


While this behaviour is by design –as a convenience method for calling once for multiple event names–, and while this could be achieved by wrapping the callback function using lodash.once, I believe there is room in this library for a method that only ever triggers for a group of events. It can be called onlyOnce or firstOnce or similar. The implementation would be minimal: simply wrap the callback in lodash.once and calling the regular once with the newly wrapped callback.

Thoughts?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions