Created
October 24, 2015 12:39
-
-
Save rudyryk/5de58fe85aa744c6ff6d to your computer and use it in GitHub Desktop.
Draft for jQuery Classify plugin
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
/*! | |
Classify plugin for binding elements to objects or functions ('classes') | |
and events to 'methods'. | |
Example: | |
var Navbar = { | |
signIn: function(evt, target) { ... }, | |
signUp: function(evt, target) { ... }, | |
}; | |
$('html').classify({ | |
Navbar: Navbar, | |
}); | |
... and HTML | |
<ul class="nav navbar-nav navbar-right" data-class="Navbar"> | |
<li> | |
<button type="button" class="btn navbar-btn" data-events="click: signUp">Sign up</button> | |
</li> | |
<li> | |
<button type="button" class="btn navbar-btn" data-events="click: signIn">Sign in</button> | |
</li> | |
</ul> | |
(c) 2015 Alexey Kinev <[email protected]> | |
The MIT License, https://opensource.org/licenses/MIT | |
*/ | |
(function ( $ ) { | |
var console = window.console || { | |
log: function() {}, | |
info: function() {}, | |
warn: function() {}, | |
error: function() {}, | |
}; | |
$.fn.classify = function( options ) { | |
if (typeof options === 'undefined') { | |
return; | |
} | |
var root = $(this); | |
$.each( options, function( name, cls ) { | |
var obj = $.isFunction( cls ) ? cls() : cls; | |
obj.element = root.find( '[data-class=' + name + ']' ); | |
obj.element.find( '[data-events]' ).addBack( '[data-events]' ).each( function() { | |
// Events binding string has format: | |
// "click: signIn, mouseover: signInOver" | |
var target = $( this ); | |
var events = target.data( 'events' ).split( ',' ); | |
$.each( events, function( i, v ) { | |
var eventInfo = v.replace( / /g, '' ).split( ':' ); | |
target.on( eventInfo[0], function( e ) { | |
var func = obj[eventInfo[1]]; | |
if (func) { | |
func.call(obj, e, target); | |
} else { | |
console.warn("Event handler not found:", name, target, e); | |
} | |
}); | |
target.trigger('init'); | |
}); | |
}); | |
}); | |
return root; | |
}; | |
}( jQuery )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment