Reputation: 73
I don't understand what each line is doing in the following snippet of JavaScript. I understand that it's reading whether the person pressed enter or escape. But I want to understand what line 2, 3, 6, 10, 16, and 18 are doing.
var okCancelEvents = function (selector, callbacks) {
var ok = callbacks.ok || function () {};
var cancel = callbacks.cancel || function () {};
var events = {};
events['keyup '+selector+', keydown '+selector+', focusout '+selector] =
function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
} else if (evt.type === "keyup" && evt.which === 13) {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value)
ok.call(this, value, evt);
else
cancel.call(this, evt);
}
};
return events;
};
Upvotes: 1
Views: 72
Reputation: 97658
A good source of JavaScript reference material is the Mozilla Developer Network.
To pick out the lines you mentioned, with links to relevant MDN pages:
callbacks.ok
or callbacks.cancel
is undefined, so that the rest of the code can know that ok
and cancel
point at a valid function.call
method, which is a way of setting an appropriate value for this
when calling a function which is not defined as a member of a particular object.The overall effect is to create an object events
, with one property, whose name lists selector
multiple times, and whose value is a function which can be passed an event and decide which of two callbacks to execute.
Note that this function doesn't include any logic for actually attaching the event to any DOM elements; the structure of its return value is presumably the input for some other function which does that.
Upvotes: 2
Reputation: 16214
var ok = callbacks.ok || function () {};
if callbacks.ok
is undefined, creates a stub
function. http://en.wikipedia.org/wiki/Method_stub and sets ok
to store reference to the that function or to reference in callbacks.ok
var cancel = callbacks.cancel || function () {};
the same for callbacks.cancel
events['keyup '+selector+', keydown '+selector+', focusout '+selector]
creates object events
(previous line) and populates its attribute 'keyup '+selector+', keydown '+selector+', focusout '+selector
with function.
cancel.call(this, evt);
calls function by reference stored in cancel
variable, with listed arguments. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
ok.call(this, value, evt);
the same, but for function reference in ok
variable.
Upvotes: 2