Skip to content

Instantly share code, notes, and snippets.

@markbrown4
Created December 7, 2010 03:58
Show Gist options
  • Save markbrown4/731434 to your computer and use it in GitHub Desktop.
Save markbrown4/731434 to your computer and use it in GitHub Desktop.
/* 1 - keep js separate */
// these are the same but #2 can be passed around.
function myFunc(a) {
}
var myFunc = function(a) {
}
// wire up events with observe
var clicker = function(event) {
var elm = Event.element(event);
console.log(elm);
Event.stop(event);
};
$('linky').observe('click', clicker);
// or anonymous function if callback doesn't need to be re-used
$('linky').observe('click', function(event) {
var elm = Event.element(event);
Event.stop(event);
});
/* 2 - Maintain scope */
// use json to group related functions / properties
var Robot = {
killCount: 0,
kill: function() {
alert('Affirmative');
Robot.killCount++;
}
}
Robot.kill();
Robot.kill();
alert('Hey Bro-bot I just got ' + Robot.killCount + ' kills. Affirmative.');
// limit scope with the self executing function
(function() {
var clutterTheGlobalSpace = false;
function doI(clutter) {
}
})();
/* Feature/object detect */
// be defensive
var elm = $('example');
if (elm) {
elm.hide();
}
if (elm) {
var content = elm.textContent ? elm.textContent : elm.innerText;
}
function jiggle(elm, options) {
options = options || {};
var duration = options.duration || 1000;
alert("I'm gonna jiggle for " + duration + " miliseconds.");
}
// 4 - Use literals to house the code
var Util = {},
Controls = {},
Page = {
launchNewWindow: function(url,options) {
}
};
// use json for optional parameters
var elm = $('example');
jiggle(elm, {
duration: 2000,
size: 10,
times: 4
});
// 5 - Efficiency
// safe references to prevent lookups
function walkTheDom(elm) {
elm = $(elm);
var wrapper = elm.up('.wrapper'),
content = elm.down('.content'),
header = elm.down('.header');
}
// the definitive for loop
var numbers = [1,2,3,4,5,6,7,8,9,10];
for (var i=0, ii=numbers.length; i<ii; i++) {
}
// create comma separated variables at the top of a block
function dance() {
var steps = [],
timer = null,
partners = [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment