jquery is tight, but when you have to resort to plain old javascript, it can be frustrating that a lot of common tasks are not dead simple or elegant. here are some syntactical shortcuts for working with objects in arrays =>
// add an object to an array
function addObj(arr,obj) {
arr.push(obj);
return arr;
}
// remove an object from array
function removeObj(arr,obj) {
arr.splice(arr.indexOf(obj), 1);
return arr;
}
// check if object is included in array
function include(arr, obj) {
for(var i=0; i=<arr.length; i++) {
if (arr[i] == obj) return true;
}
}
ever wanted to quickly create a link in rails that, when clicked, dynamically renders a partial in a targeted element? accepting bonus points for being framework agnostic? throw this puppy in your application helper =>
def remote_partial_link(*args)
name = args.first
partial = args.second
target_id = args.third
html_options = args.fourth
locals = args.fifth
if html_options
html_options = html_options.stringify_keys
tag_options = tag_options(html_options)
else
tag_options = nil
end
if locals
p = render_to_string :partial => partial, :locals => locals
else
p = render_to_string :partial => partial
end
p = escape_javascript(p).gsub("\"","'")
"<a onclick=\"document.getElementById('#{target_id}').innerHTML = '#{p}'\" "+
"#{tag_options}>#{name}</a>"
end
basically, its a bastardized version of rails built-in link_to helper. with it, in your views you can write =>
<%= remote_partial_link("Add Link", "lists/link", "link-#{i}",
{ :class => "ajax" }, { :i => i }) %>
the only limitation is that these are generated on the page’s load, so it can’t account for any remote calls that happens after that. but that also makes this solution good for performance, since the script is baked inline to the element and ready to fire. the only other piece of set-up is making the render_to_string method accessible in your helpers from your application controller =>
helper_method :render_to_string