Reputation:
Conceptually, what does eventsApi()
do? It is private to Backbone but used in 4 public event methods - on()
, once()
, off()
, and trigger()
.
In each, if it returns a non-truthy value the method calling it will exit "early".
One thing it does, is determine if the second part of the calling method will execute. If name
is not truthy or is not a complex type ( object or space separated strings ) it will return a true allowing the second part of the method to run.
What is the main purpose of the eventsApi
function, conceptually, as I have tried to describe what it does functionally/logically?
eventsAPI
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
} else if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
} else {
return true;
}
};
Upvotes: 2
Views: 213
Reputation: 5060
Like the comment in the source says, it implements the more fancy uses of the Events API.
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
So, when you use the Events API with an event map:
book.on({
"change:title": titleView.update,
"change:author": authorPane.update,
"destroy": bookView.remove
});
The eventsApi
function detects that the input is an object, and calls on
again for each of the properties passed in.
The other case it handles is space separated events:
book.on("change:title change:author", ...);
In this case, eventsApi
function detects this situation and, again, calls on
once for each of the events passed in.
Upvotes: 1