Skip to content

Instantly share code, notes, and snippets.

@vlado
Created November 5, 2013 08:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlado/7315718 to your computer and use it in GitHub Desktop.
Save vlado/7315718 to your computer and use it in GitHub Desktop.
How to extend Chosen jQuery library example
# 1. Extend Chosen with custom method or owerwrite existing methods
class CustomChosen extends Chosen
show_search_field_default: ->
# ...
# original method updated
# ...
some_new_method: ->
# ...
# 2. Extend jQuery with custom chosen (Optional, we can do custom init on app level)
$ = jQuery
$.fn.extend({
customChosen: (options) ->
# Do no harm and return as soon as possible for unsupported browsers, namely IE6 and IE7
# Continue on if running IE document type but in compatibility mode
return this unless AbstractChosen.browser_is_supported()
this.each (input_field) ->
$this = $ this
chosen = $this.data('chosen')
if options is 'destroy' && chosen
chosen.destroy()
else unless chosen
$this.data('chosen', new CustomChosen(this, options))
return
})
@dgrammatiko
Copy link

Hello,

does this code works with the latest version of Chosen?

Also can you provide plain javascript as an example, I have no clue about coffee script...

Thanks

@ZoltanT-RD
Copy link

https://decaffeinate-project.org/repl/#?useCS2=false&useJSModules=false&loose=false&evaluate=true&stage=full&code=%23%201.%20Extend%20Chosen%20with%20custom%20method%20or%20owerwrite%20existing%20methods%0D%0Aclass%20CustomChosen%20extends%20Chosen%0D%0A%20%20show_search_field_default%3A%20-%3E%0D%0A%20%20%20%20%23%20...%0D%0A%20%20%20%20%23%20original%20method%20updated%0D%0A%20%20%20%20%23%20...%0D%0A%20%20%20%20%0D%0A%20%20some_new_method%3A%20-%3E%0D%0A%20%20%20%20%23%20...%0D%0A%20%20%20%20%0D%0A%0D%0A%23%202.%20Extend%20jQuery%20with%20custom%20chosen%20(Optional%2C%20we%20can%20do%20custom%20init%20on%20app%20level)%0D%0A%24%20%3D%20jQuery%0D%0A%0D%0A%24.fn.extend(%7B%0D%0A%20%20customChosen%3A%20(options)%20-%3E%0D%0A%20%20%20%20%23%20Do%20no%20harm%20and%20return%20as%20soon%20as%20possible%20for%20unsupported%20browsers%2C%20namely%20IE6%20and%20IE7%0D%0A%20%20%20%20%23%20Continue%20on%20if%20running%20IE%20document%20type%20but%20in%20compatibility%20mode%0D%0A%20%20%20%20return%20this%20unless%20AbstractChosen.browser_is_supported()%0D%0A%20%20%20%20this.each%20(input_field)%20-%3E%0D%0A%20%20%20%20%20%20%24this%20%3D%20%24%20this%0D%0A%20%20%20%20%20%20chosen%20%3D%20%24this.data('chosen')%0D%0A%20%20%20%20%20%20if%20options%20is%20'destroy'%20%26%26%20chosen%0D%0A%20%20%20%20%20%20%20%20chosen.destroy()%0D%0A%20%20%20%20%20%20else%20unless%20chosen%0D%0A%20%20%20%20%20%20%20%20%24this.data('chosen'%2C%20new%20CustomChosen(this%2C%20options))%0D%0A%0D%0A%20%20%20%20%20%20return%0D%0A%0D%0A%7D)

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