-
lowerCamelCase
-
2 пробела для отступов
-
google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
-
Держим JS отдельно от HTML
“‘html <a href=“#” onclick=“alert(’Hello world!‘); return false;”>Click Here</a> “`
“‘html <script type=“text/javascript”charset=“UTF-8”>
$(function () { $('#alert').click(function () { alert(this.data('message')); return false; }) });
</script>
<a href=“#” id=“alert” data-message=“Hello from UJS”>Click Here</a>
“‘
-
атрибут data-something для внедренния данных в теги
<a href="#" id="alert" data-message="Hello from UJS">Click Here</a> <a href="/products/8" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a> <form action="/products" data-remote="true" method="get">
-
внедряем JS в последную очередь, когда работает простой интерфейс без JS
-
jQuery – стандарт, заменяет Prototype в 3.1 twitter.com/dhh/status/45923430608023552
-
инициализация плагинов после загрузки DOM в application.js
$(document).ready(function() { // Handler for .ready() called. });
-
content_for & yield
content_for :head do javascript_include_tag 'my_super_plugin' javascript_tag do $(document).ready(function() { $('form[data-autosubmit=true]').autoSubmit(); }) end end yield :head
-
Используй dom_id, div_for, content_tag_for для привязки JS к DOM
<ul> <% posts.each do |post| %> content_tag_for(:li, post) do <%= post.title %> end <% end %> </ul>
-
Законченный функционал в виде плагинов выделяем в отдельные файлы в public/javascript.js
-
Используем namespaces
var js = { namespace1: { function1: function() { alert('Call me!'); } } }
-
Простой плагин
(function($){ $.fn.validateCreditCardNumber = function() { return this.each(function() { $(this).blur(function() { if (!CreditCard.validNumber(this.value)) { $("#" + this.id + "_error").text("Invalid credit card number."); } else { $("#" + this.id + "_error").text(""); } }); }); }; })(jQuery);
-
Простой UI плагин
$.widget("ui.mywidget", { // default options options: { option1: "defaultValue", hidden: true }, _create: function() { // creation code for mywidget // can use this.options if (this.options.hidden) { // and this.element this.element.hide(); } }, _doSomething: function() { // internal functions should be named with a leading underscore // manipulate the widget }, value: function() { // calculate some value and return it return this._calculate(); }, length: function() { return this._someOtherValue(); }, destroy: function() { $.Widget.prototype.destroy.apply(this, arguments); // default destroy // now do other stuff particular to this widget } });
jashkenas.github.com/coffee-script/
ruby-lang.org.ru/2011/05/17/dhhs-railsconf-2011-keynote-live-blogged-here/