coffeescript

CoffeeScript variable visibility

Tagged coffeescript  Languages coffeescript

This Coffeescript:

class Device
  x: 1 # Instance variable
  y = 2 # Private instance variable
  @z: 3 # Class variable

 # Address and name are instance variables
  constructor: (@address, @name) ->

gives us this JavaScript:

Device = (function() {
  var y;
  Device.prototype.x = 1;
  y = 2;
  function Device(address, name) {
    this.address = address;
    this.name = name;
  }
  return Device;
})();

and the following visibility:

dev = new Device('X', 'Y') # => Device {address: "X", name: "Y", x: 1}
dev.y # => undefined
Device.z # => 3

Gulpfile.js example with Slim, Coffeescript, Sass, Browser Sync, Lint

Tagged gulp, slim  Languages coffeescript

A Gulpfile.js example with Slim, Coffeescript, Sass, Browser Sync, Lint. The script is suitable for building e.g. static websites and prototyping mobile apps.

Gulpfile expects your project to be structured in the following way (configurable): - src/css/*.scss,*.css - src/js/*.coffee,*.js - src/*.slim

Output is written to "www" folder.

#
# Gulpfile with:
#
# - Slim
# - Sass
# - Lint
# - Browsersync
# - CSS and HTML compression
#
# Install dependencies:
#
#   $ npm install gulp gulp-concat gulp-uglify event-stream gulp-coffee gulp-sass gulp-cssmin gulp-coffee gulp-coffeelint browser-sync gulp-util gulp-shell
#
# Then start developing:
#
#   $ gulp
#

gulp        = require 'gulp'
concat      = require 'gulp-concat'
es          = require('event-stream')
sass        = require 'gulp-sass'
uglify      = require 'gulp-uglify'
streamqueue = require 'streamqueue' # Preserves file order (vendor...)
coffee      = require 'gulp-coffee'
gutil       = require 'gulp-util'
shell       = require 'gulp-shell'
cssmin      = require 'gulp-cssmin'
coffeelint  = require 'gulp-coffeelint'
browserSync = require 'browser-sync'

isProd = gutil.env.type is 'prod'

sources =
  sass: 'src/css/**/*.scss'
  css: 'src/css/**/*.css'
  html: 'src/**/*.slim'
  js: 'src/js/**/*.js'
  coffee: 'src/js/**/*.coffee'

targets =
  css: 'www/css'
  html: 'www/'
  js: 'www/js'

# Check for errors
gulp.task 'lint', ->
  gulp.src(sources.js)
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())

# Compile Coffeescript
gulp.task 'js', ->
  stream = streamqueue(objectMode: true)
  # Vendor files
  stream.queue(gulp.src(sources.js))
  # App files use Coffee
  stream.queue(gulp.src(sources.coffee).pipe(coffee(bare:true)))
  stream.done()
    .pipe(concat("all.js"))
    .pipe(if isProd then uglify() else gutil.noop())
    .pipe(gulp.dest(targets.js))

# Compile Slim
gulp.task 'slim', ->
  gulp.src(sources.html)
    .pipe(shell(["slimrb -r ./lib/helpers.rb -p <%= file.path %> > ./#{targets.html}/<%= file.relative.replace(\".slim\", \".html\") %>"]))

# Compile CSS
gulp.task 'css', ->
  stream = streamqueue(objectMode: true)
  # Vendor files
  stream.queue(gulp.src(sources.css))
  # App files
  stream.queue(gulp.src(sources.sass).pipe(sass(style: 'expanded', includePaths: ['src/css'], errLogToConsole: true)))
  stream.done()
    .pipe(concat("all.css"))
    .pipe(if isProd then uglify() else gutil.noop())
    .pipe(gulp.dest(targets.css))

# Reload browser
gulp.task 'server', ->
  browserSync.init null,
    open: true
    server:
      baseDir: targets.html
    reloadDelay: 2000 # Prevent white screen of death
    watchOptions:
      debounceDelay: 1000

# Watch files for changes
gulp.task 'watch', ->
  gulp.watch sources.js, ['js']
  gulp.watch sources.css, ['css']
  gulp.watch sources.html, ['slim']
  gulp.watch 'www/**/**', (file) ->
    browserSync.reload(file.path) if file.type is "changed"

# Build everything
gulp.task 'build', ['lint', 'js', 'css', 'slim']

# Start a server and watch for file changes
gulp.task 'default', ['watch', 'server']

Also see A gulp.js template for React.js and ES6 projects

Automatic Instantiation of Web Components Written in JavaScript/Coffeescript

Tagged components  Languages coffeescript

Your app.js.coffee:

$ ->
  for component in $('.web-component')
    component = $(component)
    class_name = component.data('class')
    id = "#" + component.attr('id')
    component_class = eval.call(window, class_name)
    if component_class
      console.debug("Creating #{class_name}")
      try
        new component_class(id)
      catch error
        console.log "Failed to create #{class_name}"
    else
      throw "UI component '#{class_name}' does not exist."

Declare a web component in your view:

<div id="alerts" class="web-component" data-class="App.Alerts"/>

Write your web component, e.g. app/assets/javascripts/components/alert.js.coffee:

root = exports ? this
# declared elsewhere
# root.App = {}

class Alerts
....

root.App.Alerts = Alerts

A Reusable JavaScript Modal Dialog Based on Bootstrap Modal

Tagged bootstrap, modal, javascript, coffeescript  Languages coffeescript

The Coffeescript class:

root = exports ? this

class Modal
  constructor: (options = {}) ->
    @options = options
    @id = options.id ? 'modal-dialog-' + Math.round((Math.random() * 1000))
    @dom_id = "##{@id}"
    @onPrimaryButton = options.onPrimaryButton ? ->
    @onSecondaryButton = options.onSecondaryButton ? ->
    @template = options.template ? HandlebarsTemplates['modal'](id: @id)
    @render()

  render: ->
    $('body').append(@template)
    @modal = $(@dom_id)
    _this = this
    @modal.find('.btn-primary').on 'click', ->
      _this.onPrimaryButton(this)
    @modal.find('.btn-secondary').on 'click', ->
      _this.onSecondaryButton(this)

  setButtonText: (primary, secondary) ->
    @modal.find('.btn-primary').html(primary)
    @modal.find('.btn-secondary').html(secondary)

  setTitle: (title) ->
    @modal.find('.title').html(title)

  setBody: (body) ->
    @modal.find('.body').html(body)

  show: ->
    @modal.modal('show')

  hide: ->
    @modal.modal('hide')

root.Modal = Modal

The view (bootstrap 2.3.2):

<div class="modal hide fade" id="{{id}}">
  <div class="modal-header">
    <button aria-hidden="true" class="close" data-dismiss="modal" type="button"> &times;</button>
    <h3 class="title"></h3>
  </div>
  <div class="modal-body body">
  </div>
  <div class="modal-footer">
    <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
    <button class="btn btn-primary" data-dismiss="modal">Ok</button>
  </div>
</div>

Usage, e.g.:

class Notifications
  constructor:  ->
    @modal = new Modal
      onPrimaryButton: $.proxy(@onItemDelete, this)
      onSecondaryButton: $.proxy(@onItemRead, this)
  onItemDelete: ->
    # do something when primary button was clicked
  onItemRead: ->
    # do something when secondary button was clicked