Permalink
Browse files

switch to rails-behaviors

  • Loading branch information...
1 parent d4e87be commit 8af1263fed90448f7a94def1314b7f0c952b6fa5 @mislav committed Nov 7, 2011
View
@@ -26,6 +26,7 @@ gem 'escape_utils'
gem 'choices' #, :path => '/Users/mislav/Projects/choices'
gem 'never-forget' #, :path => '/Users/mislav/Projects/never-forget'
gem 'twin' #, :path => '/Users/mislav/Projects/twin'
+gem 'rails-behaviors'
group :extras do
gem 'nokogiri', '~> 1.4.1'
View
@@ -133,6 +133,8 @@ GEM
rack
rack-test (0.6.1)
rack (>= 1.0)
+ rails-behaviors (0.1.0)
+ sprockets (~> 2.0)
railties (3.1.0)
actionpack (= 3.1.0)
activesupport (= 3.1.0)
@@ -239,6 +241,7 @@ DEPENDENCIES
never-forget
nibbler (~> 1.1)
nokogiri (~> 1.4.1)
+ rails-behaviors
railties (~> 3.1.0)
rspec-rails (~> 2.6.1)
ruby-debug
@@ -1,18 +1,18 @@
-$(document).delegate '.actions input[type=submit].watched', 'click', ->
- $(this).closest('.actions').addClass('asking')
- false
-
-$(document).delegate '.actions input[type=submit].watched', 'ajax:before', ->
- false
+$(document).on
+ click: ->
+ $(this).closest('.actions').addClass('asking')
+ false
+ ajaxBeforeSend: -> false
+, '.actions input[type=submit].watched'
-$(document).delegate '.actions .question a[href="#cancel"]', 'click', ->
+$(document).on 'click', '.actions .question a[href="#cancel"]', ->
$(this).blur().closest('.actions').removeClass('asking')
false
-$(document).delegate '.actions .button_to', 'ajax:success', (e, html) ->
+$(document).on 'ajaxSuccess', '.actions .button_to', (e, xhr, settings, html) ->
replaceActions $(this).closest('.actions'), html
-$(document).delegate 'a.revert', 'ajax:success', (e, html) ->
+$(document).on 'ajaxSuccess', 'a.revert', (e, xhr, settings, html) ->
replaceActions $(this).closest('.actions'), html
# preserve the ".other-info" element while replacing ".actions"
@@ -1,5 +1,5 @@
//= require zepto
-//= require ujs
+//= require rails
//= require_tree .
//= require facebox
@@ -1,111 +0,0 @@
-fire = (el, name, data) ->
- event = $.Event(name)
- el.trigger(event, data)
- not event.defaultPrevented
-
-handleRemote = (element) ->
- return unless fire(element, 'ajax:before')
- if element.is('form')
- method = element.attr('method')
- url = element.attr('action')
- data = element.serializeArray()
- # memoized value from clicked submit button
- element.data 'ujs:submit-button', (i, button) ->
- data.push button if button
- null
- else
- method = element.data('method')
- url = element.attr('href')
- data = element.data('params') || null
-
- ajaxOptions =
- type: method || 'GET'
- data: data
- headers:
- Accept: '*/*;q=0.5, ' + $.ajaxSettings.accepts.script
- beforeSend: (xhr, settings) ->
- return fire(element, 'ajax:beforeSend', [xhr, settings])
- success: (data, status, xhr) ->
- element.trigger('ajax:success', [data, status, xhr])
- complete: (xhr, status) ->
- element.trigger('ajax:complete', [xhr, status])
- error: (xhr, status, error) ->
- element.trigger('ajax:error', [xhr, status, error])
-
- ajaxOptions.url = url if url
-
- token = $('meta[name="csrf-token"]').attr('content')
- ajaxOptions.headers['X-CSRF-Token'] = token if token
-
- $.ajax(ajaxOptions)
-
-handleMethod = (link) ->
- href = link.attr('href')
- method = link.data('method')
- csrf_token = $('meta[name=csrf-token]').attr('content')
- csrf_param = $('meta[name=csrf-param]').attr('content')
- form = $("<form method='post' action='#{href}'></form>")
- hidden = "<input name='_method' value='#{method}' type='hidden' />"
-
- if csrf_param? and csrf_token?
- hidden += "<input name='#{csrf_param}' value='#{csrf_token}' type='hidden' />"
-
- form.hide().append(hidden).appendTo('body')
- form.submit()
-
-disableSelector = 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]'
-enableSelector = 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled'
-
-disableFormElements = (form) ->
- form.find(disableSelector).each ->
- element = $(this)
- method = if element.is('button') then 'html' else 'val'
- element.data('enable-with', element[method]())
- element[method](element.data('disable-with'))
- element.attr('disabled', 'disabled')
-
-enableFormElements = (form) ->
- form.find(enableSelector).each ->
- element = $(this)
- method = if element.is('button') then 'html' else 'val'
- element[method](element.data('enable-with')) if element.data('enable-with')
- element.removeAttr('disabled')
-
-allowAction = (element) ->
- message = element.data('confirm')
- not message or confirm(message)
-
-$(document).delegate 'form[data-remote]', 'submit', (e) ->
- element = $(this)
- handleRemote element if allowAction element
- false
-
-$(document).delegate 'form:not([data-remote])', 'submit', (e) ->
- disableFormElements $(this)
-
-$(document).delegate 'form', 'ajax:beforeSend', (e) ->
- disableFormElements $(this) if this is e.target
-
-$(document).delegate 'form', 'ajax:complete', (e) ->
- enableFormElements $(this) if this is e.target
-
-buttonSelector = 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])'
-
-$(document).delegate buttonSelector, 'click', ->
- button = $(this)
- name = button.attr('name')
- data =
- if name
- name: name
- value: button.val()
-
- button.closest('form').data('ujs:submit-button', data)
-
-$(document).delegate 'a[data-remote], a[data-method]', 'click', (e) ->
- element = $(this)
- if allowAction element
- if element.data('remote') isnt null
- handleRemote element
- else
- handleMethod element
- false
@@ -1,202 +0,0 @@
-(function() {
- Ajax.Responders.register({
- onCreate: function(request) {
- var token = $$('meta[name=csrf-token]')[0];
- if (token) {
- if (!request.options.requestHeaders) request.options.requestHeaders = {};
- request.options.requestHeaders['X-CSRF-Token'] = token.readAttribute('content');
- }
- }
- });
-
- // Technique from Juriy Zaytsev
- // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
- function isEventSupported(eventName) {
- var el = document.createElement('div');
- eventName = 'on' + eventName;
- var isSupported = (eventName in el);
- if (!isSupported) {
- el.setAttribute(eventName, 'return;');
- isSupported = typeof el[eventName] == 'function';
- }
- el = null;
- return isSupported;
- }
-
- function isForm(element) {
- return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM';
- }
-
- function isInput(element) {
- if (Object.isElement(element)) {
- var name = element.nodeName.toUpperCase();
- return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA';
- }
- else return false;
- }
-
- var submitBubbles = isEventSupported('submit'),
- changeBubbles = isEventSupported('change');
-
- if (!submitBubbles || !changeBubbles) {
- // augment the Event.Handler class to observe custom events when needed
- Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
- function(init, element, eventName, selector, callback) {
- init(element, eventName, selector, callback);
- // is the handler being attached to an element that doesn't support this event?
- if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
- (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
- // "submit" => "emulated:submit"
- this.eventName = 'emulated:' + this.eventName;
- }
- }
- );
- }
-
- if (!submitBubbles) {
- // discover forms on the page by observing focus events which always bubble
- document.on('focusin', 'form', function(focusEvent, form) {
- // special handler for the real "submit" event (one-time operation)
- if (!form.retrieve('emulated:submit')) {
- form.on('submit', function(submitEvent) {
- var emulated = form.fire('emulated:submit', submitEvent, true);
- // if custom event received preventDefault, cancel the real one too
- if (emulated.returnValue === false) submitEvent.preventDefault();
- });
- form.store('emulated:submit', true);
- }
- });
- }
-
- if (!changeBubbles) {
- // discover form inputs on the page
- document.on('focusin', 'input, select, textarea', function(focusEvent, input) {
- // special handler for real "change" events
- if (!input.retrieve('emulated:change')) {
- input.on('change', function(changeEvent) {
- input.fire('emulated:change', changeEvent, true);
- });
- input.store('emulated:change', true);
- }
- });
- }
-
- function handleRemote(element) {
- var method, url, params;
-
- var event = element.fire("ajax:before");
- if (event.stopped) return false;
-
- if (element.tagName.toLowerCase() === 'form') {
- method = element.readAttribute('method') || 'post';
- url = element.readAttribute('action');
- // serialize the form with respect to the submit button that was pressed
- params = element.serialize({ submit: element.retrieve('rails:submit-button') });
- // clear the pressed submit button information
- element.store('rails:submit-button', null);
- } else {
- method = element.readAttribute('data-method') || 'get';
- url = element.readAttribute('href');
- params = {};
- }
-
- new Ajax.Request(url, {
- method: method,
- parameters: params,
- evalScripts: true,
-
- onCreate: function(response) { element.fire("ajax:create", response); },
- onComplete: function(response) { element.fire("ajax:complete", response); },
- onSuccess: function(response) { element.fire("ajax:success", response); },
- onFailure: function(response) { element.fire("ajax:failure", response); }
- });
-
- element.fire("ajax:after");
- }
-
- function insertHiddenField(form, name, value) {
- form.insert(new Element('input', { type: 'hidden', name: name, value: value }));
- }
-
- function handleMethod(element) {
- var method = element.readAttribute('data-method'),
- url = element.readAttribute('href'),
- csrf_param = $$('meta[name=csrf-param]')[0],
- csrf_token = $$('meta[name=csrf-token]')[0];
-
- var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
- $(element.parentNode).insert(form);
-
- if (method !== 'post') {
- insertHiddenField(form, '_method', method);
- }
-
- if (csrf_param) {
- insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content'));
- }
-
- form.submit();
- }
-
- function disableFormElements(form) {
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.store('rails:original-value', input.getValue());
- input.setValue(input.readAttribute('data-disable-with')).disable();
- });
- }
-
- function enableFormElements(form) {
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.setValue(input.retrieve('rails:original-value')).enable();
- });
- }
-
- function allowAction(element) {
- var message = element.readAttribute('data-confirm');
- return !message || confirm(message);
- }
-
- document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
- if (!allowAction(link)) {
- event.stop();
- return false;
- }
-
- if (link.readAttribute('data-remote')) {
- handleRemote(link);
- event.stop();
- } else if (link.readAttribute('data-method')) {
- handleMethod(link);
- event.stop();
- }
- });
-
- document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
- // register the pressed submit button
- event.findElement('form').store('rails:submit-button', button.name || false);
- });
-
- document.on("submit", function(event) {
- var form = event.findElement();
-
- if (!allowAction(form)) {
- event.stop();
- return false;
- }
-
- if (form.readAttribute('data-remote')) {
- handleRemote(form);
- event.stop();
- } else {
- disableFormElements(form);
- }
- });
-
- document.on('ajax:create', 'form', function(event, form) {
- if (form == event.findElement()) disableFormElements(form);
- });
-
- document.on('ajax:complete', 'form', function(event, form) {
- if (form == event.findElement()) enableFormElements(form);
- });
-})();

0 comments on commit 8af1263

Please sign in to comment.