2014-06-08 3 views
1

서버가 참/거짓 데이터를 데이터베이스로 보내는 동안 원격 링크를 비활성화해야하는 토글이 있습니다. 그런 다음 ajax:success에서 링크를 다시 사용하도록 설정합니다.일시적으로 레일을 비활성화 원격 링크

$('body').on('click', '.toggle_link', function(){ 
    //disable remote link 
}) 

$('body').on('ajax:success', '.toggle_link', function(){ 
    //enable remote link 
}) 

이를 달성하기위한 가장 좋은 방법이 있나요 :

나는

내가 이런 일을 할 수 있기를 원하는 레일 원격 링크에 e.preventDefault()를 사용하지 못할?

답변

3

이렇게하면 원격 링크가 비활성화되어야합니다.

$('#remote_link').removeAttr('data-remote').removeAttr('href') 

는 일부 data 속성 ( data-target 또는 떨어지게)에서 대상 URL을 저장하고 ajax:success에 다시 href을 가져올 수를 다시 활성화합니다.

1

클릭하면 링크를 비활성화하려면 write it's jquery in your asset pipeline 수 있습니다. e.preventDefault()을 사용할 수 없으므로 간단히 change it's href to #을 사용하십시오. data-href 속성을 사용하면 원래 링크가 다시 포함되어 다시 활성화됩니다 (많은 링크가 있고 어디로 갈지 모를 경우).

$('body').on('click', '.toggle_link', function(){ 
    $(this).prop("href", "#"); 
}); 

을하고 당신이 할 수있는 다시 재 활성화 : 그래서 JQuery와 파일 안에 당신이 할 수있는

레일에서
$('body').on('ajax:success', '.toggle_link', function(){ 
    var url = $(this).data("href"); 
    $(this).prop("href",url); 
}); 

js.erb 파일은 아약스입니다 : 성공. 따라서 jserver 파일 전체에 Ajax : success 코드를 작성하는 대신 js.erb 파일에 작성할 수는 있지만, 어떻게 든 data-href의 값을 컨트롤러에 보내야합니다 (이미 URL을 모르면 링크). 다음 단계에 따라 수행 할 수 있습니다.

a. routes.rb 파일의 post URL을 사용자 지정 작업으로 만듭니다.

b. 귀하의 js 파일에 아약스 전화를 작성하십시오 :

c. 맞춤 작업 내에서 해당 URL을 가져올 수 있습니다. @url = params[:data-url]

d. 당신이 할 수있는 당신의 js.erb 파일 간단한 쓰기 내부

$("#some_id_of_link").prop("href",@url); 
+0

나는 완벽한 전략이라고 생각합니다. – Graeme

2

무엇 나를 위해 일하는 결국은 user2675613의 대답의 일부가 다음 또한 data-remote="true"data-method="put" 속성을 제거를 사용했다.

//to disable 
var url_link = $(this).attr('href'); 
$(this).attr('data-href', url_link); 
$(this).attr('href', "#"); 
$(this).removeAttr('data-remote'); 
$(this).removeAttr('data-method'); 

//to enable 
var url_link = $(this).attr('data-href'); 
$(this).attr("href", url_link); 
$(this).attr("data-remote", "true"); 
$(this).attr("data-method", "put"); 

이것은 업데이트 작업을위한 것이므로 데이터 메서드를 저장할 수있는 작업에 따라 다릅니다.

+0

왜 데이터 - 원격 및 데이터 - 방법을 제거 하시겠습니까? 당신의 href가 이미 '#'라면 그 두가지를 제거하고자하는 이유는 무엇입니까? – Mandeep

+0

@ user2675613 링크가 여전히 빈 요청을 보내는 것을 끝내기 때문에 링크를 완전히 비활성화합니다. – Graeme

2

ujs의 ajax:beforeSend 이벤트에 연결할 수도 있습니다.그들이 link_to 때이 remote: true의 동작을 비활성화하는 데 사용되는 '장애인'

$(document).on('ajax:beforeSend', 'a.disabled[data-remote=true]', function(event, xhr, status, error) { 
    event.preventDefault(); 
    event.stopImmediatePropagation(); 
    return false; 
    }); 
0

의 CSS 클래스를했을 때

$(document).on('ajax:beforeSend', 'a[data-remote=true]', function(event, xhr, status, error) { 
    // stash the link 
    // remove the href 
    }); 

나는 실행 데이터 원격 링크를 방지하기 위해이의 세인 것을 사용 disabled 속성을 추가합니다. 따라서 상황을보다 깔끔하게 처리 할 수 ​​있습니다.

$('a[data-remote]').on('ajax:beforeSend', function(event, xhr, settings) { 
    if($(this).attr('disabled') == 'true' || $(this).attr('disabled') == 'disabled') { 
    return false; 
    } 
}); 
관련 문제