Last active
August 29, 2015 13:59
-
-
Save johnpolacek/10892759 to your computer and use it in GitHub Desktop.
Simple jQuery Pattern for doing cool data-binding stuff using jQuery.on() and jQuery.trigger() - see the demo at http://cdpn.io/mhCai
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"> | |
<head> | |
<meta charset="utf-8"> | |
<title>title</title> | |
</head> | |
<body> | |
<p>Simple jQuery Pattern for doing cool data-binding stuff using <code>jQuery.on()</code> and </code>jQuery.trigger()</code></p> | |
<h1>Messages</h1> | |
<div id="output"></div> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<script> | |
// Example of extending an empty jQuery object and using it to pass data around | |
var messageObj = $.extend($({}),(function(o) { | |
// Private Things | |
var data = { | |
message:'', | |
totalMessages:0, | |
totalChars:0 | |
}; | |
// Public Things | |
o.setMessage = function(msg) { | |
data.message = msg; | |
if (msg === '') { | |
o.trigger('message.delete'); | |
} else { | |
data.totalMessages++; | |
data.totalChars += msg.length; | |
o.trigger('message.set',[data]); | |
} | |
return o; | |
}; | |
o.getMessage = function() { | |
return message; | |
}; | |
return o; | |
})($({}))); | |
// Define your handlers | |
messageObj | |
.on('message.set', function(e, data) { | |
$('#output').append('<p>'+data.message+'<br><small><em>Total Messages Sent: '+data.totalMessages+' ('+data.totalChars+' characters)</em></small></p>'); | |
}) | |
.on('message.delete', function() { | |
$('#output').append('<p>Message deleted. No message for you.</p>'); | |
}); | |
// Do stuff | |
messageObj | |
.setMessage('Hi. I am a jQuery Object that you can use for cool data-binding stuff.') | |
.setMessage('Use jQuery.on() and jQuery.trigger() for passing data around.') | |
.setMessage('') | |
.setMessage('Created by John Polacek(@johnpolacek) Inspired by Ben Howdle(@benhowdle)'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment