I am trying to understand Todos example in Meteor. There's a piece of code that I can't make sense of:
// Returns an event map that handles the "escape" and "return" keys and
// "blur" events on a text input (given by selector) and interprets them
// as "ok" or "cancel".
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 ||
evt.type === "focusout") {
// 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;
};
What does events['keyup '+selector+', keydown '+selector+', focusout '+selector] = function(){}
yield?
Why do we need to convert to string the following: String(evt.target.value || "")
?
Does evt argument of the said function have to have .type, .target and .target.value? What I can pass in evt?
I've broken the question into its three parts:
What does events['keyup '+selector+', keydown '+selector+', focusout '+selector] = function(){} yield?
The okCancelEvents
method is a way to wrap keyup
, keydown
and focusout
DOM events around a single function that curates the details of each function's outcome into a custom ok
or cancel
event.
This yields an EventMap
object that is bound to the Template.todos.events
implementation so that all keyup
, keydown
, and focusout
events come through as ok
or cancel
via the EventMap
.
Why do we need to convert to string the following: String(evt.target.value || "")?
I don't think this is necessary. var value = evt.target.value || ""
works just as well because the browser will interpret a string primitive as a string object.
Does evt argument of the said function have to have .type, .target and .target.value? What I can pass in evt?
The evt
argument is the passed-in event
from the keyup
, keydown
, and focusout
methods and target
and target.value
are baked-in properties of this native event
object. You don't need to construct this by hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With