You can render a partial from within your js.erb using the following syntax:
<%= render :partial => "shared/alerts" %>
Just put your code above into a partial in the appropriate directory. In my above example, the file would be called _alerts.js.erb and you'd put the partial in a directory I called shared (which would be in your views directory), but you can choose whatever directory you deem appropriate.