Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save timurvafin/913449 to your computer and use it in GitHub Desktop.
Save timurvafin/913449 to your computer and use it in GitHub Desktop.

Стандарты кодирования

Unobtrusive JavaScript

  • Держим 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

  • asciicasts.com/episodes/205-unobtrusive-javascript

jQuery & Rails

  • 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>

Кортроллер возвращает JS - это все еще круто и хорошо

Модульность

  • Законченный функционал в виде плагинов выделяем в отдельные файлы в 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
      }
    });

CoffeScript

jashkenas.github.com/coffee-script/

Sprockets v2

getsprockets.org/

PJAX

pjax.heroku.com/

node.js

ruby-lang.org.ru/2011/05/17/dhhs-railsconf-2011-keynote-live-blogged-here/

@timurvafin
Copy link
Author

$(document).ready ->
  $('form[data-autosubmit=true]').autoSubmit()

@timurvafin
Copy link
Author

js = 
  namespace: 
    test: ->
      alert 'test'

js.namespace.test();

@timurvafin
Copy link
Author

(($) -> 
  $.fn.validateCreditCardNumber = -> 
    this.each -> 
      if not CreditCard.validNumber this.value 
        $("#" + this.id + "_error").text "Invalid credit card number."
      else
        $("#" + this.id + "_error").text ""
)(jQuery);

@timurvafin
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment