Reputation: 143
Can anybody tell me what this code means?
var func = tool[ev.type];
if (func) {
func(ev);
}
tool is a function declared upun this sentece.
Upvotes: -1
Views: 62
Reputation: 2011
In addition to the answer above, looking at a simpler (and full) example may be helpful in understanding what's going on here, from a pure JavaScript perspective.
function Tool() {
this.test = function(param) { // create a new method called 'test' on our Tool object
console.log(param); // output the value of 'param' to the console
}
}
var tool = new Tool(); // Create a new Tool
var func = tool['test']; // assign the 'test' method of 'tool' to the 'func' variable
func("input"); // run the 'func' function with "input" as the parameter
Upvotes: 1
Reputation: 2509
It's referencing a property on the function (Object) "tool", which apparently contains another function in itself. Testing to make sure the function exists, then invoking that function.
tool is an object filled with event handlers, the property names in the object "tool" correspond to the different type of events. The code is referencing the property in the "tool" object based on the event "type." For example:
var tool = {
'click': function(evt) {}, // event handler for click
'mousedown': function(evt) {}, // event handler for mousedown
'mouseup': function(evt) {}, // event handler for mouseup
}
// User presses the mouse button down and doesn't release.
// ev.type == 'mousedown'
//
// Save the property value (which should be an event handler)
// to a variable.
var func = tool[ev.type];
// Make sure func is defined before attempting to invoke it.
if (func) {
// func is defined, invoke it and pass the event object to it
func(ev);
}
Hope this helps! :)
Upvotes: 1