Skip to content

Instantly share code, notes, and snippets.

@subzey
Forked from thingsinjars/LICENSE.txt
Created December 19, 2011 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subzey/1496936 to your computer and use it in GitHub Desktop.
Save subzey/1496936 to your computer and use it in GitHub Desktop.
Chainable property setting
// Function to add properties in a chainable manner either as single strings or as an object
// usage:
// object.prop('propertyName', propertyValue)
// or:
// object.prop({'propertyNameOne':'propertyValueOne','propertyNameTwo':'propertyValueTwo'})
function(
a // Constructor
){
a.prototype.prop = function(b, c){ // Add prop method to prototype
/* note: value of `a` arg is unused from now and may be reused */
1 in arguments // Arguments' length is >= 2?
? // If yes,
(a = {})[b] = c // `a` is a new object with only property
: // otherwise,
a = b // `a` is `b` (1st argument)
;
/* note: values of `b` and `c` args are unused from now */
for (b in a) // For each property
this[b] = a[b] // Set its name and value to this
;
return this // Finally, return `this` for chaining
}
}
function(a){a.prototype.prop=function(b,c){1 in arguments?(a={})[b]=c:a=b;for(b in a)this[b]=a[b];return this}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Simon Madine <http://thingsinjars.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "propertize",
"description": "This allows properties to be added to an object in a chainable manner",
"keywords": [
"DOM",
"properties",
"chaining"
]
}
<!DOCTYPE html>
<meta charset="utf-8">
<title>Chain anything</title>
<div>Expected value: <b><a href="http://140byt.es/" title="tiny awsm" data-monkeys="∞">140byt.es</a></b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var propertize = function(a){a.prototype.prop=function(b,c){1 in arguments?(a={})[b]=c:a=b;for(b in a)this[b]=a[b];return this}}
// see https://gist.github.com/gists/1466219 (enable DOM manipulation chaining)
var chainify = function(a,b,c){for(a in b=a.prototype)with({d:b[a]})d.call?b[a]=function(){return(c=d.apply(this,arguments))===a._?this:c}:0}
chainify(window.Element);
propertize(window.Element);
document.getElementById('ret').appendChild(
document.createElement('a')
.prop({
'href': 'http://140byt.es/',
'title': 'tiny awsm'
})
.prop('innerHTML', '140byt.es')
.setAttribute('data-monkeys', '∞')
.addEventListener('click', function(){ alert('Urk! Alert!')}, false)
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment