AJAX&Jquery

From Hawk Wiki
Revision as of 02:45, 3 April 2012 by Hall (Talk | contribs) (Created page with "==JavaScript== Closure. <pre> <script> function say667() { // Local variable that ends up within closure var num = 666; //var sayAlert = function() { alert(num); } re...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

JavaScript

Closure.

<script>
function say667() {
  // Local variable that ends up within closure
  var num = 666;
  
  //var sayAlert = function() { alert(num); }
  return function() { num++; alert(num); };
}

var sayNumba = say667();
sayNumba();
sayNumba();
</script>

The example will keep var num in the memory. alert 667 and 668 on each call;

Jquery Data & Attribute

<a id="foo" data-foo="bar" href="#">foo!</a> The data can then be accessed using .data() in jQuery:

console.log( $('#foo').data('foo') ); //outputs "bar" However when you store data on a DOM node in jQuery using data, the variables are stored in on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.

continuing my example from above:

$('#foo').data('foo', 'baz');

console.log( $('#foo').attr('data-foo') ); //outputs "bar" as the attribute was never changed

console.log( $('#foo').data('foo') ); //outputs "baz" as the value has been updated on the object Also, the naming convention for data attributes has a bit of a hidden "gotcha":

<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a> console.log( $('#bar').data('fooBarBaz') ); //outputs "fizz-buzz" as hyphens are automatically camelCase'd