| 1 |
// Zepto.js |
| 2 |
// (c) 2010-2012 Thomas Fuchs |
| 3 |
// Zepto.js may be freely distributed under the MIT license. |
| 4 |
|
| 5 |
// The following code is heavily inspired by jQuery's $.fn.data(); |
| 6 |
(function($) { |
| 7 |
var data = {}, |
| 8 |
dataAttr = $.fn.data, |
| 9 |
camelize = $.zepto.camelize, |
| 10 |
exp = $.expando = 'Zepto' + (+new Date()) |
| 11 |
|
| 12 |
// Get value from node: |
| 13 |
// 1. first try key as given, |
| 14 |
// 2. then try camelized key, |
| 15 |
// 3. fall back to reading "data-*" attribute. |
| 16 |
function getData(node, name) { |
| 17 |
var id = node[exp], |
| 18 |
store = id && data[id] |
| 19 |
if (name === undefined) return store || setData(node) |
| 20 |
else { |
| 21 |
if (store) { |
| 22 |
if (name in store) return store[name] |
| 23 |
var camelName = camelize(name) |
| 24 |
if (camelName in store) return store[camelName] |
| 25 |
} |
| 26 |
return dataAttr.call($(node), name) |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
// Store value under camelized key on node |
| 31 |
function setData(node, name, value) { |
| 32 |
var id = node[exp] || (node[exp] = ++$.uuid), |
| 33 |
store = data[id] || (data[id] = attributeData(node)) |
| 34 |
if (name !== undefined) store[camelize(name)] = value |
| 35 |
return store |
| 36 |
} |
| 37 |
|
| 38 |
// Read all "data-*" attributes from a node |
| 39 |
function attributeData(node) { |
| 40 |
var store = {} |
| 41 |
$.each(node.attributes, function(i, attr) { |
| 42 |
if (attr.name.indexOf('data-') == 0) store[camelize(attr.name.replace('data-', ''))] = $.zepto.deserializeValue(attr.value) |
| 43 |
}) |
| 44 |
return store |
| 45 |
} |
| 46 |
|
| 47 |
$.fn.data = function(name, value) { |
| 48 |
return value === undefined ? |
| 49 |
// set multiple values via object |
| 50 |
$.isPlainObject(name) ? this.each(function(i, node) { |
| 51 |
$.each(name, function(key, value) { |
| 52 |
setData(node, key, value) |
| 53 |
}) |
| 54 |
}) : |
| 55 |
// get value from first element |
| 56 |
this.length == 0 ? undefined : getData(this[0], name) : |
| 57 |
// set value on all elements |
| 58 |
this.each(function() { |
| 59 |
setData(this, name, value) |
| 60 |
}) |
| 61 |
} |
| 62 |
|
| 63 |
$.fn.removeData = function(names) { |
| 64 |
if (typeof names == 'string') names = names.split(/\s+/) |
| 65 |
return this.each(function() { |
| 66 |
var id = this[exp], |
| 67 |
store = id && data[id] |
| 68 |
if (store) $.each(names, function() { |
| 69 |
delete store[camelize(this)] |
| 70 |
}) |
| 71 |
}) |
| 72 |
} |
| 73 |
})(Zepto) |