С примерами на Coffeescript
(a) -> a * a # function(a){ return a * a; } // omg!
@ # this
class Javascript extends Language
constructor: (@dialect='ecma') ->
getKeywords: (which='used') ->
keywords =
used: [ 'var', 'const', 'in', 'for' ]
unused: ['class', 'export', 'import' ]
keywords[which] || null
echo: () ->
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) ->
@ # <- this
options # <- object
defaultOptions = {}
@.each -> # коллекцию возвращаем
options = $.extend {}, defaultOptions, options
# do stuff
Хорошо бы иметь такое API:
# создали виджет
$('#selector').mywidget({opt: ions})
# дергаем метод
$('#selector').mywidget( 'show', 'message')
$.fn.myPlugin = (options, args..) ->
class MyPlugin
constructor: (@element, @options) ->
oneMethod: () ->
anotherOne: (props) ->
defaultOptions = {}
@.each ->
obj = @data 'myplugin'
unless obj
options = $.extend {}, defaultOptions, options
obj = new MyPlugin @, options
@data 'myplugin', obj
else
method = options
obj[method].apply obj, args if method
Где бы хотелось расширить методы jQuery?
jQuery.cssHooks.cats =
get: (elem, computed, extra) ->
'300 ms'
set: (elem, value) ->
# do something to cats
jQuery.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 = # @ == elem
noBubble: true
# самый первый/самый последний обработчик
setup: (data, ns, eventHanle) ->
teardown: (ns, eventHandle) ->
# очередной обработчик
add: (handleObj) -> #handleObj.handle
remove: (handleObj) ->
jQuery.event.special.custom = # @ == elem
trigger: (data) ->
handle: (event) ->
_default: (data) ->
preDispatch: (event) ->
postDispatch: (event) ->
jQuery.event.special.beforeunload =
setup: ( data, namespaces, eventHandle )
if jQuery.isWindow( this )
this.onbeforeunload = eventHandle
teardown: ( 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 == 0
data.triggered || $(@).trigger 'empty'
data.triggered = true
else if data.triggered
data.triggered = false
, 100)
teardown: ( namespaces, eventHandle ) ->
clearInterval jQuery.data(@, 'empty_event').timer
jQuery.ajaxSetup
accepts:
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 transport
send: (headers, callback) ->
#do stuff
abort: () ->
#omg, abort
else
#return fallback transport optionaly
Пример: поиск незагруженных картинок
jQuery.expr[':'].mailto = (node, index, props, nodes) ->
if node.href && node.href.match /^mailto:/
unless props[3]
true
else
node.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