Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Last active April 13, 2017 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagdeepsingh/e7630f2aeacd48e050a0 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/e7630f2aeacd48e050a0 to your computer and use it in GitHub Desktop.
Javascript, jQuery, Coffeescript

Javascript

forEach

ary = [11, 22, 33, 44, 55]
ary.forEach(function(value, index, array){
  // ...
});

jQuery

ajax

Submit a form using jQuery.ajax.

var $form, data, url;
$form = $('#resreview-form');
url = $form.attr('action');
data = $form.serializeJSON();

$.ajax({
  url: url,
  type: 'POST',
  data: data,
  dataType: 'json'
});

Coffeescript

Define a class

We are defining a class window.User below.

class window.User
  @min_age: 18
  
  contructor: (selector, name, age) ->
    @$elem = $(selector)
    @name = name
    @age = age
    @likes = []
    @bind_events()
  
  bind_events: ->
    @$elem.on 'click', => @print_info()

  print_info: ->
    alert("Name: #{@name}, Age: #{@age}")

  add_like: (value) ->
    @likes.push value

Here is a usage of variables and methods defined above.

User.min_age                          // 18

user = new User('Jagdeep Singh', 28)
user.add_like('Domino')
user.likes                            // ['Domino']

user_2 = new User('JP Duminy', 33)
user_2.add_like('KFC')
user_2.likes                          // ['KFC']

More

class window.Reservation
  @foo_bool: true
  @foo_regex: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^A-Za-z0-9])/

  @expressions: ->
    foo is bar
    foo isnt bar
    foo is not bar

  @selectors: ->
    $(':radio')
    $(':radio:checked')
    $(':radio[checked="checked"]')
    $(':checkbox')
    $(':checkbox:checked')

  @events: ->
    $(selector).on 'click', child_selector, ->
      Foo.clicked()

    $(selector).on 'click', =>
      @clicked()

    $(selector).on 'click', ->
      Foo.clicked()

    $(selector, selector_2).on 'click', ->
      Foo.clicked()

    # Other events are 'change', 'keyup'

  # Methods
  @ordersData: -> $('#new-reservation-orders')

  @ordersData: ->
    $('#new-reservation-orders')

  @ordersData: (num) ->
    $('#new-reservation-orders')[num]

  # arguments with default values
  @foo: (a, b = 1, c = 2) ->
    @bar(a, b, c)

  @bindEvents: ->
    @someOtherMethodOfThisClass()
  
    # Bind event using `on`
    $('#reservation').on 'submit', (event) ->
      ReservationCourses.foo()

    $('#reservation').on 'submit', (event) =>
      @foo()

    $('#parent-selector').on 'change', '.child-selector', (event) =>
      @foo()

    # Check conditions
    if condition then doSomething else doSomethingElse

    if conditionOne
      doSomething
    else if conditionTwo
      doSomethingElse
    else
      doNothing

    doSomething if condition
    doSomething if conditionOne or conditionTwo
    doSomething if conditionOne and conditionTwo
    @foo() unless condition

    return conditionOne or
    conditionTwo or
    conditionThree
    
    a = if condition then 1 else 2

    # `switch`
    switch key
      when 'foo' then @foo()
      when 'bar' then @bar()

    switch key
      when 'foo'
        @foo()
      when 'bar'
        @bar()

    # Map
    $.map someArrayOrJqueryObject, (element, idx) ->
      @doSomething(element)

    # ajax
    $.ajax
      url: someUrl
      type: 'GET'
      data: { date: date }
      dataType: 'json'
      beforeSend: ->
        @showLoader()
      success: (data) ->
        ReservationCourses.doSomething(data)

    # Loops
    $.each menuItems, (i, menuItem) ->
      # ...

    menuItems.each (i, menuItem) ->
      # ...

    while min <= max
      @foo()
      min += 1

    # Get common elements from 2 arrays
    $(ids).filter(otherArray).toArray()

    # `filter`
    $numbers.filter (num) ->
      some_boolean_expression

    $rowElements.filter (i, row) ->
      some_boolean_expression

 # show bootstrap modal
 @showModal: ->
   $element.modal()
   $element.modal('show')
   $element.modal({ backdrop: 'static' })
   $element.modal({ keyboard: false })

 # hide bootstrap modal
 @hideModal: ->
   $element.modal('hide')
$(function(){
foo();
});
$(checkbox).is(':checked');
jQuery.ready.then(function() {
foo();
}).fail(function(error) {
throw error;
})
// Add function $.fn.goTo() to scroll to an element on page
// Usage: $(selector).goTo()
(function(jQuery) {
jQuery.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 1000);
return this;
};
})(jQuery);
class window.ScrollToExtension
@init: ->
# Usage: `$(selector).goTo();`
((jQuery) ->
jQuery.fn.goTo = ->
$('html, body').animate({ scrollTop: $(this).offset().top + 'px' }, 1000)
this
return
)(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment