On Tue, Jun 28, 2011 at 3:23 PM, Ian Hickson <ian@hixie.ch> wrote:
> On Mon, 27 Jun 2011, Cameron McCormack wrote:
>>
>> In Web IDL currently, if you write [Callback] on an interface and the
>> interface consists of a single operation, then script can implement that
>> interface either by using a Function object, or by providing an object
>> with a property whose name is the identifier of the operation.
>
> I've always assumed that the latter was a side-effect of non-JS languages
> needing something more complicated here than just a function reference: if
> the old DOM specs had never targetted anything but JS, would we support
> the non-function case? Consider setTimeout(), which only takes a function
> (or a string, for legacy reaons).
>
>
>> Olli gave a good example of why you might want to allow objects-with-a-
>> property to be used as callback objects, which is so that you can
>> encapsulate some state in that object.
>>
>> Â var handler = {
>> Â Â _highlighted: false,
>> Â Â handleEvent: function(evt) {
>> Â Â Â this._highlighted = !this._highlighted;
>> Â Â Â evt.target.style.color = this._highlighted ? "red" : "black";
>> Â Â }
>> Â };
>> Â e.addEventListener("click", handler, false);
>
> (function () {
> Â var highlighted = false;
> Â e.addEventListener("click", function (event) {
> Â Â highlighted = !highlighted;
> Â Â event.target.style.color = highlighted ? "red" : "black";
> Â }, false);
> })();
I'm not really sure either of these syntaxes have an obvious upper hand.
However the latter syntax seems problematic if you're also using this
object for things other than simply being a event handler. I.e. if
have an object representing the chat "window" as seen in for example
gmail chat and facebook chat. Such an object would want to listen to
click events when the user clicks to expand/collapse the chat window.
But it would also provide public API that can be called by for example
a websocket handler receiving an event indicating that a new chat is
starting, or if the user leaves the page in which case the chat needs
to be closed down in a controlled manner.
On the other hand, you can always bridge the gap between a object with
handleEvent and a function by changing
addEventListener("foo", someObject, false);
to
addEventListener("foo", someObject.handleEvent.bind(someObject), false);
People claimed that using the object syntax has started to see some
uptake. I'd be curious to hear why those developers have chosen that
syntax.
/ Jonas