Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

Rails 4: DOM is ready and AJAX response leads to duplication

Question

Is there a good technique to avoid calling the same code javascript(jquery) in AJAX responses?

Example

Lets say I have these views and js files

index.html.erb

<div class="listing_users">
  <%= render @users %>
</div>

_user.html.erb

<div class="user">
    <%= @user.name %>
</div>

users.js

$(document).ready(function() {
  $(".user").css({"background-color": "red"})
})

When I create a new user through AJAX I make rails render this in my create.js.erb response.

$(".listing_users").append("<%= j(render(:partial => @users)) %>")
$(".listing_users").css({"background-color": "red"})

The $(".listing_users").css({"background-color": "red"}) line needs to be there for the newly rendered partial.

Possible solution

I am aware that I just can make a function like this

function set_red(){
  $(".user").css({"background-color": "red"})
}

and just call it both in when the DOM is ready and in the AJAX response. But, this also calls the code two times.

Upvotes: 0

Views: 119

Answers (1)

collapsar
collapsar

Reputation: 17258

You can share a jquery 'deferred' object between the ready handler and the ajax callback.

The done method of this object would contain your code, while you call its resolve method from within the ajax callback and the ready handler.

The resolution takes place only once, even if requested multiple times.

code sample:

// jquery must have been included here
var g_cbguard = new Deferred();
g_cbguard
    .done(function () {
        // your code that shall be executed only once
    })
;
// ...

// ready handler
$(document).ready(function () {
    // ...
    g_cbguard.resolve();
    // ...
});
// ...

// somewhere else in your ajax call
$.ajax(
    //...)
).done( function () {
    g_cbguard.resolve();
});
// ...

Upvotes: 1

Related Questions