JavaScript/Notes/ParameterObject: Difference between revisions
Created page with "Passing around lists of parameters? Typechecking arguments? Stop doing that. Here's how to make your code clearer and less error-prone. The DOM event methods for creating eve..." |
No edit summary |
||
| Line 9: | Line 9: | ||
touchEvent = doc.createEvent("TouchEvent"); | touchEvent = doc.createEvent("TouchEvent"); | ||
if (typeof touchEvent.initTouchEvent == "function") { | |||
touchEvent.initTouchEvent(type, bubbles, cancelable, view, | |||
detail, screenX, screenY, pageX, pageY, ctrlKey, | |||
altKey, shiftKey, metaKey, touches, targetTouches, | |||
changedTouches, scale, rotation); | |||
// fire the event | // fire the event | ||
canceled = target.dispatchEvent(touchEvent); | canceled = target.dispatchEvent(touchEvent); | ||
} | } | ||
</source> | </source> | ||
18 parameter variables is too many. Instead, we can pass in an object. | |||
Like this: | |||
<source lang="javascript"> | |||
fireTouchEvent("touchend", target, options); | |||
</source> | |||
Where <code>options</code> has a corresponding property for each argument. | |||
See also [http://c2.com/cgi/wiki?TooManyParameters]. | |||
Revision as of 09:17, 31 October 2013
Passing around lists of parameters? Typechecking arguments? Stop doing that. Here's how to make your code clearer and less error-prone.
The DOM event methods for creating events are an example of what not to do. My comments on w3c DOM mailing list led to the current Event constructor.
Method initTouchEvent (Apple) is fine example of terrible design. Here's how to change that.
<source lang="javascript">
var touchEvent, canceled;
touchEvent = doc.createEvent("TouchEvent"); if (typeof touchEvent.initTouchEvent == "function") {
touchEvent.initTouchEvent(type, bubbles, cancelable, view, detail, screenX, screenY, pageX, pageY, ctrlKey, altKey, shiftKey, metaKey, touches, targetTouches, changedTouches, scale, rotation); // fire the event canceled = target.dispatchEvent(touchEvent);
} </source> 18 parameter variables is too many. Instead, we can pass in an object.
Like this:
<source lang="javascript">
fireTouchEvent("touchend", target, options);
</source>
Where options has a corresponding property for each argument.
See also [1].