Open dhritzkiv opened 8 years ago
interesting. i expected the behavior you expected as well. i'm not sure that this isn't a bug*
onlyOnce
makes sense as a name to me, and I wonder if once
with multiple names should log a warning. I for one would have fallen into the same assumption. Agreeing w/ @cdaringe that this could even be considered a bug (the fixing of which would probably necessitate a major version however)
The tests indicate that isn't not a insidious bug in as much as the tests specifically expect the callback to be called for each event name. (https://github.com/AmpersandJS/ampersand-events/blob/master/test/index.js#L528)
The reason for this expectation, I believe, is Backbone's events works this way (I found out through Stackoverflow, where other devs were confused by this behaviour too). Check out this assertion example (using Backbone event instead of ampersand-events) to see for yourselves
What really confuses me is the expected behaviour after reading through the code logic of ampersand-event's once
:
once: function (name, callback, context) {
var self = this;
var once = runOnce(function () {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
}
it seems that callback
is being wrapped inside a function that also calls off
to remove this particular listener for any future events for this name
, and then that function is then being wrapped in lodash.once
. Not sure if that's right.
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:see live example on TonicDev
But I misunderstood the functionality. There were rare cases where both
success
anderror
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 thecallback
function usinglodash.once
, I believe there is room in this library for a method that only ever triggers for a group of events. It can be calledonlyOnce
orfirstOnce
or similar. The implementation would be minimal: simply wrap thecallback
inlodash.once
and calling the regularonce
with the newly wrapped callback.Thoughts?