5. Global variables are
bound implicitly.
Usually to the window object.
var easy = 'absolutely';
easy === window.easy; // true
easy === this.easy; // true
6. Variables cascade
into functions.
var easy = 'absolutely';
function areYouSure() {
alert( easy ); // absolutely
}
8. Functions are objects.
function myFunc() { return true; }
var myFunc = function() { return true; };
9. Functions are closures.
function safe() {
var secret = 'sshhh!';
}
alert( secret ); // Error: undefined!
10. Don’t forget to use var!
Otherwise, your variables are declared globally.
function safe() {
secret = 'sshhh!';
}
// Uh oh...
alert( secret ); // 'sshhh!'
11. Functions are nestable.
var a = 1;
function outer() {
var b = 2;
function inner() {
var c = 3;
alert( a + b + c ); // 6
}
alert( a + b + c ); // Error: c is undefined!
}
12. Functions can be anonymous.
jQuery(document).click( function(){
alert('Hello, world.');
});
21. Except when it doesn’t.
var context = 'global',
obj = {
context: 'object',
getContext: function() { alert( this.context ); }
},
except = obj.getContext;
// We expect 'object', but see 'global'!
except(); // global
28. Loading jQuery
wp_enqueue_script('jquery');
or
wp_enqueue_script( 'slug', 'file.js', array('jquery'),
'2.0', true );
Don’t just print <script> tags.
Use wp_enqueue_script wherever possible.
29. WordPress uses
jQuery.noConflict
jQuery.noConflict disables the $ variable.
To use $ again, wrap your code in this:
(function($){ /* code code code */ })(jQuery);
30. AJAX in WordPress: PHP
// Action for admin
add_action("wp_ajax_$my_action", 'my_action_callback');
// Action for frontend
add_action("wp_ajax_$my_action", 'my_action_callback');
add_action("wp_ajax_nopriv_$my_action", 'my_action_callback');
Do not use $_REQUEST[‘action’] in place of $my_action.
31. AJAX in WordPress: JS
jQuery.post( ajaxurl, {
action: myAction
}, function( data ) {
// response code
});
32. AJAX in WordPress
On the front end, ajaxurl is not defined.
function koop_ensure_ajaxurl() {
add_action( 'wp_head', '__koop_ensure_ajaxurl' );
}
function __koop_ensure_ajaxurl() {
if ( is_admin() )
return;
?><script type="text/javascript">
//<![CDATA[
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
//]]>
</script><?php
}
33. Patch core with
SCRIPT_DEBUG
define( 'SCRIPT_DEBUG', true );
While you’re at it, use WP_DEBUG:
define( 'WP_DEBUG', true );
44. Use the ready event.
Properly.
(function($){
// Non-DOM related code.
$(document).ready( function() {
// Code that traverses or manipulates the DOM
});
})(jQuery);