Skip to content

Commit

Permalink
- return 0s for offset() when element is not found
Browse files Browse the repository at this point in the history
  • Loading branch information
ded committed Nov 2, 2011
1 parent 7aa9665 commit 88fe000
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 23 deletions.
51 changes: 38 additions & 13 deletions bonzo.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
, uidList = []
, uuids = 0
, digit = /^-?[\d\.]+$/
, dattr = /^data-(.+)$/
, px = 'px'
, setAttribute = 'setAttribute'
, getAttribute = 'getAttribute'
Expand Down Expand Up @@ -79,6 +80,23 @@
})
}

function decamelize(s) {
return s ? s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() : s
}

function data(el) {
el[getAttribute]('data-node-uid') || el[setAttribute]('data-node-uid', ++uuids)
uid = el[getAttribute]('data-node-uid')
return uidList[uid] || (uidList[uid] = {})
}

function dataValue(d) {
try {
return d === 'true' ? true : d === 'false' ? false : d === 'null' ? null : !isNaN(d) ? parseFloat(d) : d;
} catch(e) {}
return undefined
}

function isNode(node) {
return node && node.nodeName && node.nodeType == 1
}
Expand Down Expand Up @@ -232,11 +250,11 @@
}

, first: function () {
return bonzo(this[0])
return bonzo(this.length ? this[0] : [])
}

, last: function () {
return bonzo(this[this.length - 1])
return bonzo(this.length ? this[this.length - 1] : [])
}

, html: function (h, text) {
Expand Down Expand Up @@ -441,6 +459,12 @@
xy(el, x, y)
})
}
if (!this[0]) return {
top: 0
, left: 0
, height: 0
, width: 0
}
var el = this[0]
, width = el.offsetWidth
, height = el.offsetHeight
Expand Down Expand Up @@ -515,19 +539,20 @@
}

, data: function (k, v) {
var el = this[0], uid, o
var el = this[0], uid, o, m
if (typeof v === 'undefined') {
el[getAttribute]('data-node-uid') || el[setAttribute]('data-node-uid', ++uuids)
uid = el[getAttribute]('data-node-uid')
uidList[uid] || (uidList[uid] = {})
return uidList[uid][k]
o = data(el)
if (typeof k === 'undefined') {
each(el.attributes, function(a) {
(m = (''+a.name).match(dattr)) && (o[camelize(m[1])] = dataValue(a.value))
})
return o
} else {
return typeof o[k] === 'undefined' ?
(o[k] = dataValue(this.attr('data-' + decamelize(k)))) : o[k]
}
} else {
return this.each(function (el) {
el[getAttribute]('data-node-uid') || el[setAttribute]('data-node-uid', ++uuids)
uid = el[getAttribute]('data-node-uid')
o = uidList[uid] || (uidList[uid] = {})
o[k] = v
})
return this.each(function (el) { data(el)[k] = v })
}
}

Expand Down
Loading

0 comments on commit 88fe000

Please sign in to comment.