Created
February 28, 2011 16:52
-
-
Save pavenuto/847603 to your computer and use it in GitHub Desktop.
Playing around with Paul Irish's plugin factory and data- attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en" class="no-js"> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
<link rel="stylesheet" href="css/style.css"> | |
<style type="text/css" media="screen"> | |
.cell {display: inline-block; background: #FCF7CA; padding: 10px; position: absolute; font: bold 16px Helvetica, Arial, sans-serif;} | |
.w-1 {width: 80px;} | |
.w-2 {width: 160px;} | |
.w-3 {width: 240px;} | |
.x-1 {left: 10px;} | |
.x-3 {left: 200px;} | |
</style> | |
</head> | |
<body> | |
<div data-layout='{"x":"1","w":"2"}'> | |
Hello | |
</div> | |
<div data-layout='{"x":"3","w":"1"}'> | |
There | |
</div> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> | |
<script> | |
// jquery plugin factory | |
// by Paul Irish. public domain | |
// https://github.com/paulirish/jQuery-miniplugins/blob/master/pluginfactory.js | |
$.plugin = function(name, object) { | |
// create a new plugin with the given name | |
$.fn[name] = function(options) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
return this.each(function() { | |
// check the data() cache, if it's there we'll call the method requested | |
var instance = $.data(this, name); | |
if (instance) { | |
options && instance[options].apply(instance, args); | |
} else { | |
// if a constructor was passed in... | |
if (typeof object === 'function') instance = new object(options, this); | |
// else an object was passed in | |
else { | |
// create a constructor out of it | |
function F(){}; | |
F.prototype = object; | |
instance = new F() | |
instance.init(options,this); | |
} | |
$.data(this, name, instance); | |
} | |
}); | |
}; | |
}; | |
$.plugin("gridLayout", { | |
init: function(options, element) { | |
this.$elem = $(element); | |
this.setup(); | |
}, | |
setup: function(){ | |
var x = this.$elem.data('layout').x, | |
w = this.$elem.data('layout').w; | |
this.$elem.addClass("cell w-"+w+" x-"+x); | |
}, | |
teardown: function(){ | |
this.$elem.removeAttr('class'); | |
} | |
}); | |
$(function(){ | |
$('div').gridLayout(); | |
// $('div').gridLayout("teardown"); | |
// console.log($('div').data('gridLayout')); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment