С примерами на Coffeescript
(a) -> a * a # function(a){ return a * a; } // omg!@ # this
class Javascript extends Languageconstructor: (@dialect='ecma') ->getKeywords: (which='used') ->keywords =used: [ 'var', 'const', 'in', 'for' ]unused: ['class', 'export', 'import' ]keywords[which] || nullecho: () ->words = @getKeywords 'unused'console.log "#{word}" for word in words
var Javascript,__hasProp = {}.hasOwnProperty,__extends = function(child, parent) { for (var key in parent) {if (__hasProp.call(parent, key)) child[key] = parent[key]; }function ctor() { this.constructor = child; }ctor.prototype = parent.prototype; child.prototype = new ctor();child.__super__ = parent.prototype; return child; };Javascript = (function(_super) {__extends(Javascript, _super);
function Javascript(dialect) {this.dialect = dialect != null ? dialect : 'ecma';}Javascript.prototype.getKeywords = function(which) {var keywords;if (which == null) {which = 'used';}
keywords = {used: ['var', 'const', 'in', 'for'],unused: ['class', 'export', 'import']};return keywords[which] || null;};Javascript.prototype.echo = function() {var word, _i, _len, _ref, _results;
_ref = getKeywords('unused');_results = [];for (_i = 0, _len = _ref.length; _i < _len; _i++) {word = _ref[_i];_results.push(console.log("" + word + " is reserved"));}return _results;};return Javascript;})(Language);
jQuery - сборник плагинов
$.fn.myPlugin = (options) ->@ # <- thisoptions # <- objectdefaultOptions = {}@.each -> # коллекцию возвращаемoptions = $.extend {}, defaultOptions, options# do stuff
Хорошо бы иметь такое API:
# создали виджет$('#selector').mywidget({opt: ions})# дергаем метод$('#selector').mywidget( 'show', 'message')
$.fn.myPlugin = (options, args..) ->class MyPluginconstructor: (@element, @options) ->oneMethod: () ->anotherOne: (props) ->defaultOptions = {}
@.each ->obj = @data 'myplugin'unless objoptions = $.extend {}, defaultOptions, optionsobj = new MyPlugin @, options@data 'myplugin', objelsemethod = optionsobj[method].apply obj, args if method
Где бы хотелось расширить методы jQuery?
jQuery.cssHooks.cats =get: (elem, computed, extra) ->'300 ms'set: (elem, value) -># do something to catsjQuery.cssProps.cats = 'mscats' # алиасjQuery.cssNumber.cats = true # хотим работать с числом
# алиас для длительностиjQuery.extend jQuery.fx.speeds, { uberfast: 100 }# функция для анимированияjQuery.easing.bumble =(percent, current, start, stop, duration) ->percent * (10 - percent * 9)
Уже не нужно, но еще можно!
jQuery.fx.cats = (tween) ->jQuery.style(tween.elem, tween.prop,tween.now + tween.unit)
jQuery.event.special.custom = # @ == elemnoBubble: true# самый первый/самый последний обработчикsetup: (data, ns, eventHanle) ->teardown: (ns, eventHandle) -># очередной обработчикadd: (handleObj) -> #handleObj.handleremove: (handleObj) ->
jQuery.event.special.custom = # @ == elemtrigger: (data) ->handle: (event) ->_default: (data) ->preDispatch: (event) ->postDispatch: (event) ->
jQuery.event.special.beforeunload =setup: ( data, namespaces, eventHandle )if jQuery.isWindow( this )this.onbeforeunload = eventHandleteardown: ( namespaces, eventHandle ) ->if this.onbeforeunload == eventHandle@onbeforeunload = null
jQuery.event.special.empty =setup: ( data, namespaces, eventHandle ) ->jQuery.data(elem = @, data = {})data.timer = setInterval(=>if elem.innerHTML.length == 0data.triggered || $(@).trigger 'empty'data.triggered = trueelse if data.triggereddata.triggered = false, 100)
teardown: ( namespaces, eventHandle ) ->clearInterval jQuery.data(@, 'empty_event').timer
jQuery.ajaxSetupaccepts:script: "text/javascript, application/javascript"contents:script: /javascript|ecmascript/converters:"text script": ( text ) ->jQuery.globalEval text
jQuery.ajaxPrefilter "script", (s, origs, jqXHR) ->#prepare stuff"anothertype"
jQuery.ajaxTransport "transport", (s) ->if condition# return transportsend: (headers, callback) ->#do stuffabort: () ->#omg, abortelse#return fallback transport optionaly
Пример: поиск незагруженных картинок
jQuery.expr[':'].mailto = (node, index, props, nodes) ->if node.href && node.href.match /^mailto:/unless props[3]trueelsenode.href.replace(/^.*@/, '') == props[3]
Для использования функционала jQuery не обязательно использовать коллекции
param, Callbacks, Deffered, camelCase, contains, each, extend, inArray, isArray, grep, isEmptyObject, isFuction, isNumeric, isPlainObject, isWindow, isXmlDoc, makeArray, map, merge, noop, now, parseJSON, proxy, queue, trim, unique