Skip to content

Instantly share code, notes, and snippets.

@mdzzohrabi
Created August 22, 2015 13:56
Show Gist options
  • Save mdzzohrabi/e90fb8afeadc5622279f to your computer and use it in GitHub Desktop.
Save mdzzohrabi/e90fb8afeadc5622279f to your computer and use it in GitHub Desktop.
jQuery additional features
# Orginal methods and variable
Base = {
jQuery:
append: jQuery.fn.append
val: jQuery.fn.val
remove: jQuery.fn.remove
}
window.Base = Base
do( $ = jQuery , window ) ->
# Append event for jQuery
jQuery.fn.append = ->
Base.jQuery.append.apply( this , arguments ).trigger 'append', arguments[0]
# Remove event for jQuery
jQuery.fn.remove = ->
$('*',this).trigger 'remove',arguments[0]
Base.jQuery.remove.apply( this , arguments )
# Clone attributes
jQuery.fn.cloneAttrs = ( source , except ) ->
props = {}
except = [] if not except?
$.each source.get(0).attributes, ()->
props[ @.name ] = @.value if except.indexOf( @.name ) < 0
@.attr props
# Value change event
jQuery.fn.val = ->
val = Base.jQuery.val.apply( this , arguments )
$(this).trigger 'value' , arguments if arguments.length > 0
val
# Map a collection of elements to an Object
jQuery.fn.mapTo = ( selector , obj , key , val ) ->
mapped = []
mapItem = ( index , item )->
return false if mapped.indexOf(item) >= 0
mapped.push item
$this = $ item
k = if key? then key $this else index
updateValue = () =>
v = if val? then val $this else $this.val()
obj[k] = v
$this
.one 'remove', (e)->
i = mapped.indexOf this
delete mapped[i]
delete obj[k]
.on 'keyup', updateValue
.on 'change', updateValue
updateValue()
true
$( selector , this ).each ( index ) ->
mapItem index, this
$(this).on 'append', (e)->
node = $ e.target
node = node.find selector
items = $ selector,this
node.each ()->
mapItem items.index(this), this
true
@mdzzohrabi
Copy link
Author

jQuery additional features

  • Append event
  • Remove event
  • Pragmatically value change event
  • Clone attributes from another element
  • Map collection of elements to an Object

Append event

$('body').on('append', function(event){
     console.log( event.target )
})

Remove event

$('button').on('remove', function(event){
     console.log( event.target )
})

Clone attributes

cloneAttrs( source )
$('#div_1').cloneAttrs( $('#div_2') )

Map to Object

mapTo( selector , object , [KeyFunction] , [ValueFunction] )
var Form = {}
$('form').mapTo( 'input,select,textarea' , Form , function( obj ){
       return obj.attr('id');
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment