阅读更多
JavaScriptGenerator
摘自:《OReilly.RJS.Templates.for.Rails.Jun.2006.chm》chapter 7
The following is a list of all of the methods public methods offered by the JavaScriptGenerator. These methods are called on the page object in your RJS templates.
Since RJS is all about generating JavaScript, it is nice to know what is going on behind the scenes. Knowing about the JavaScript that is generated makes it much easier to debug problems and create more complex applications. At some point, your RJS code may become too complex or there may be a task that you can't perform elegantly with RJS. If you understand how RJS generates JavaScript, you can easily port your code into a JavaScript library and use RJS to access your new JavaScript objects and methods.
Therefore, for all of the following definitions, I have placed the JavaScript that the method generates after the Ruby code. The Ruby code is marked with the comment # Ruby code, and the JavaScript is marked with // Generated JavaScript.
<<(javascript)
Writes raw JavaScript to the page.
[](id)
Returns a JavaScriptElementProxy for the DOM element with the specified id. Methods can be called on the returned element. Multiple method calls can also be chained together.
# Ruby code
page['header'].show
// Generated JavaScript
$("header").show();
# Ruby code
page['header'].first.second
// Generated JavaScript
$("header").first().second();
assign(variable, value)
Assigns a value to the JavaScript variable specified. Ruby objects are automatically converted to JavaScript objects by calling the object's to_json method if it has one, or inspect if it doesn't.
# Ruby code
page.assign 'name', { :first => "Cody", :last => "Fauser" }
// Generated JavaScript
name = { "first": "Cody", "last": "Fauser" };
alert(message)
Displays a JavaScript alert dialog box with the provided message.
# Ruby code
page.alert 'An error occurred while processing your request'
// Generated JavaScript
alert("An error occurred while processing your request");
call(function, arg, ...)
Calls a JavaScript function and passes in zero or more arguments.
# Ruby code
page.call 'displayError', 'An error occurred', 'Critical'
// Generated JavaScript
displayError("An error occurred", "Critical");
You can call methods on custom objects that you've added to your page by specifying the variable name and the method call.
# Ruby code
page.call 'inventory.showTotal'
// Generated JavaScript
inventory.showTotal();
delay(seconds = 1)
Executes the code within the block after delaying for the specified number of seconds.
# Ruby code
page.delay(5) do
page.visual_effect :highlight, 'navigation'
end
// Generated JavaScript
setTimeout(function() {
;
new Effect.Highlight("navigation", {});
}, 5000);
draggable(id, options = {})
Makes the DOM element specified by the id draggable.
# Ruby code
page.draggable('photo', :revert => true)
// Generated JavaScript
new Draggable('photo', {revert: true});
drop_receiving( id, options = {})
Makes the DOM element specified by the id receive dropped draggable elements. Draggable elements are created using the RJS draggable method or by using draggable_element() Scriptaculous helper.
# Ruby code
page.drop_receiving('photo', :url => { :action => 'add' })
// Generated JavaScript
Droppables.add("photo", {onDrop:function(element){new
Ajax.Request('/hello_world/add', {asynchronous:true, evalScripts:true,
parameters:'id=' + encodeURIComponent(element.id)})}});
hide(id, ...)
Hides one or more DOM elements. Specify the elements to hide by their DOM ids.
# Ruby code
page.hide('first', 'second')
// Generated JavaScript
Element.hide("first", "second");
insert_html(position, id, *options_for_render)
Inserts the HTML into the specified position in relation to the element.
The available positions are:
:before
The content is inserted into the page before the element.
:after
The content is inserted into the page after the element.
:top
The content is inserted into the element before the element's existing content.
:bottom
The content is inserted into the element after the element's existing content.
# Ruby code
page.insert_html(:bottom, 'products', '
Refrigerator')
// Generated JavaScript
new Insertion.Bottom("products", "
Refrigerator");
redirect_to(location)
Redirect the browser to the location specified. redirect_to() passes the location to url_for(), so any of the arguments you normally use with url_for() can also be used with redirect_to().
# Ruby code
page.redirect_to('http://www.google.com')
// Generated JavaScript
window.location.href = "http://www.google.com";
# Ruby code
page.redirect_to(:controller => 'inventory', :action => 'list')
// Generated JavaScript
window.location.href = "http://localhost:3000/inventory/list";
remove(id, ...)
Removes one or more DOM elements from the page.
# Ruby code
page.remove('first', 'second')
// Generated JavaScript
["first", "second"].each(Element.remove);
replace(id, *options_for_render)
Replaces the entire element specified or outerHTML. replace is useful with partial templates so that the entire partial, which includes a container element, can be rendered and used to replace content during an RJS call. An example is an unordered list. A partial containing a
tag can be rendered instead of having to replace the innerHTML of the . Replacing just the innerHTML would require the tag to be moved out of the partial.
# Ruby code
product.replace 'banner', 'Welcome back Cody '
// Generated JavaScript
Element.replace("banner", "
Welcome back Cody ");
replace_html(id, *options_for_render)
Replaces the content or innerHTML of the DOM element with the id with either a String or the output of a rendered partial template.
# Ruby code
page.replace_html 'timestamp', Time.now
// Generated JavaScript
Element.update("timestamp", "Sat Apr 29 15:14:24 EDT 2006");
select(pattern)
Selects DOM elements using CSS-based selectors. Returns a JavaScriptElementCollectionProxy that can then receive proxied enumerable methods. See the JavaScriptCollectionProxy methods in the next section.
# Ruby code
page.select "#content p"
// Generated JavaScript
# => $$("#content p");
sortable(id, options = {})
Makes the element with the DOM ID id sortable using drag and drop. The options are the same as the options for ScriptaculousHelper#sortable_element().
# Ruby code
# Assuming the current controller is ProjectsController
page.sortable 'project-65', :url => { :action => 'sort' }
// Generated JavaScript
Sortable.create("project-65", {onUpdate:function(){
new Ajax.Request('/projects/sort', {
asynchronous:true, evalScripts:true, parameters:Sortable.serialize("project-65")
}
)}
});
show(id, ...)
Makes one or more hidden DOM elements visible. As with hide(), the elements are specified by their DOM ids.
# Ruby code
page.show 'element-20', 'element-30'
// Generated JavaScript
Element.show("element-20", "element-30");
toggle(id, ...)
Toggles the visibility of one or more DOM objects.
# Ruby code
page.toggle 'product-1', 'product-2', 'product-3'
// Generated JavaScript
Element.toggle("product-1", "product-2", "product-3");
visual_effect(name, id = nil, options = {})
Creates a new Scriptaculous visual effect to the element with the DOM id. See the following section on visual effects for a list of the visual effects shipping with Rails 1.1.
# Ruby code
page.visual_effect :highlight, 'list-item-69', :duration => 5
// Generated JavaScript
new Effect.Highlight("list-item-69",{duration:5});
JavaScriptElementProxy
The JavaScriptElementProxy is a proxy to a real DOM object. You can proxy method calls to the any of the DOM object's JavaScript methods. A few additional methods have been added to the proxy objects to make them more useful. This reference covers those enhanced non-JavaScript methods.
replace_html(*options_for_render)
Replaces the innerHTML of the DOM object. See the JavaScriptGenerator#replace_html() method for more information.
replace(*options_for_render)
Replaces the outerHTML for the DOM object. See JavaScriptGenerator#replace() method for more information.
reload
Reloads the content for the element by re-rendering a partial with the same name as the DOM element's id.
page['header'].reload
# Equivalent to:
page['header'].replace :partial => 'header'
JavaScriptCollectionProxy
The JavaScriptCollectionProxy is the most difficult part of RJS to understand and work with. This section will first cover some of the trickier aspects of the enumerable support and the actual reference will begin. This will help you avoid trouble and maintain your productivity.
Block Variables and the Enumerable methods
JavaScriptGenerator#select() returns an instance of the JavaScriptElementCollectionProxy class. JavaScriptElementCollectionProxy inherits from JavaScriptCollectionProxy, which provides all of the functionality. The trickiest part about the collection proxy enumerable methods is the code that goes within the block. The code within the block is translated into a JavaScript iterator function. Another tricky aspect of the enumerable block is that you can use any variable names you like for the block parameters, but in the generated JavaScript iterator function the variable names used are always value and index. This rule applies to any expression you use within the block that isn't a simple method called on the proxy object.
The first block parameter is always the element and the second is always the index, except with inject() and pluck(). If you don't access the value or index within the block, then you don't have to pass them into the block. In the following example, the block parameter is named element.
# Ruby code
page.select('#elements span').all('allVisible') do |element, index|
element.visible
end
// Generated JavaScript
var allVisible = $$("#elements span").all(function(value, index) {
return value.visible();
});
As you can see from the generated JavaScript, the variable value was used and not element, as it was named in the Ruby code. This works well, as long as the code within the block is a simple proxied method call, as it was in the preceding code. More complex expressions need to be written as a string and passed to the << method of the page object.
When using a direct element proxy rather than a string passed to <<, the generator assumes that the proxied call is a method call and automatically adds (). This means that you can't directly proxy an element's property, such as element.innerHTML.
page.select('#elements span').any('allVisible') do |value, index|
page << '!value.visible()'
end
The last expression in the block is the statement appended to the return statement in the generated JavaScript code, so it is possible to safely add more method calls to the block.
Inspecting the Results of the Enumerations
The one problem with the enumerable functions is that it is difficult to inspect the return JavaScript variables assigned by the function. The FireBug console is unable to display the assigned variable when the variable is assigned during the execution of eval() after an Ajax call. I used a small Logger class that uses the printfire() method discussed in the FireBug chapter to log to the JavaScript console. I then created a simple class to inspect the JavaScript variables assigned by the enumerable functions. You can define the class in public/javascripts/application.js.
var Inspector = {}
Inpsector = {
inspect: function(val) {
if (val.innerHTML) {
Logger.log(val.innerHTML);
} else {
Logger.log(val);
}
},
inspectArray: function(array) {
array.each(this.inspect);
}
}
Following is an example of the usage of the Logger class for inspecting the variable assigned by the return value of sort_by(). In this case sort_by() sorts all the paragraphs in the page by the length of their content and stores the sorted objects in an Array named sortedParagraphs.
page.select('p').sort_by('sortedParagraphs') do |value, index|
page << 'value.innerHTML.length;'
end
page << 'Logger.inspectArray(sortedParagraphs);'
This code simply iterates through the sorted paragraphs and displays the HTML content of each object to the FireBug console. Feel free to expand and improve on the code to meet your own needs.
Method Reference
All of the following enumerable methods are simply proxies to the Prototype enumerable method of the same name. For each method (except for pluck), there is a corresponding Ruby enumerable method with the same name. The Ruby enumerable method may have an added ? (e.g., all?). The Prototype methods were meant to mimic Ruby's enumerable methods. Therefore, you can get a pretty good idea of the overall intent of each method by examining the Ruby version.
all(variable) {|value,index| block }
Each element is passed to the block. The block is converted to a JavaScript iterator function. The JavaScript variable is set to TRue if the iterator function never returns false or null.
# Ruby code
page.select('#line-items li').all('allVisible') do |value, index|
value.visible
end
// Generated JavaScript
var allVisible = $$("#line-items li").all(function(value, index) {
return value.visible();
});
any(variable){|value, index| block }
Each element is passed to the block. The block is converted to a JavaScript iterator function. The JavaScript variable is set to TRue if the iterator function never returns false or null.
# Ruby code
page.select('#line-items li').any('anyVisible') do |value, index|
value.visible
end
// Generated JavaScript
var anyVisible = $$("#line-items li").any(function(value, index) {
return value.visible();
});
collect(variable){|value, index| block }
The block is converted to a JavaScript iterator. This method assigns a new JavaScript Array to the JavaScript variable containing the results of executing the iterator function once for each element.
# Ruby code
page.select('#orders tr').collect('heights') do |value, index|
value.get_height
end
// Generated JavaScript
var heights = $$("#orders tr").collect(function(value, index) {
return value.getHeight();
});
detect(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to the first element for which the iterator function does not return false.
# Ruby code
page.select('#content p').detect('first_visible') do |value, index|
value.visible
end
// Generated JavaScript
var first_visible = $$("#content p").detect(function(value, index) {
return value.visible();
});
each{|value, index| block }
Passes each element to the block, which is converted to a JavaScript iterator function. The iterator function is called once for each element.
# Ruby code
page.select('#content p').each do |value, index|
page << 'alert(value.innerHTML);'
end
// Generated JavaScript
$$("p").each(function(value, index) {
alert(value.innerHTML);
});
find(variable){|value, index| block }
A synonym for JavaScriptCollectionProxy#detect().
find_all(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to an Array of all elements for which the iterator function does not return false.
# Ruby code
page.select('#content p').find_all('empty_paragraphs') do |value, index|
value.empty
end
// Generated JavaScript
var empty_paragraphs = $$("#content p").collect(function(value, index) {
return value.empty();
});
grep(variable, pattern){|value, index| block }
Each DOM element with a toString() matching the Regexp pattern is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to an Array containing the results of executing the iterator function once for each element.
This method isn't entirely useful in the context of RJS. Its only real use is matching DOM elements using the pattern based on their type, which is output by the toString() method. The toString() method outputs [object HTMLDivElement] for a element. Use the FireBug console to view the toString() output for other elements.
# Ruby code
page.select('#content p').grep('hidden', /Div|Paragraph/) do |value, index|
value.hidden
end
// Generated JavaScript
var hidden = $$("#content p").grep(/Div|Paragraph/, function(value, index) {
return value.hidden();
});
inject(variable, memo){|memo, value, index| block }
Each element and the accumulator value memo is passed to the given block. The block is converted to a JavaScript iterator function. The iterator function is called once for each element and the result is stored in memo. The result returned to the JavaScript variable is the final value of memo. The initial value of memo is set in one of two ways. The value of the parameter memo is used as the initial value if a non nil value is passed in to the method. Otherwise, the first element of the collection is used as the initial value.
# Ruby code
page.select('#content .columns').inject('totalWidth', 0) do |memo, value, index|
page << '(memo + value.offsetWidth)'
end
// Generated JavaScript
var totalWidth = $$(".columns").inject(0, function(memo, value, index) {
return(memo + value.offsetWidth);
});
map(variable){|value, index| block }
Synonym for JavaScriptCollectionProxy#collect().
max(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to the largest value returned by the iterator function.
# Ruby code
page.select('p').max('longestParagraphLength') do |value, index|
page << 'value.innerHTML.length'
end
// Generated JavaScript
var longestParagraphLength = $$("p").max(function(value, index) {
return value.innerHTML.length;
});
min(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to the smallest value returned by the iterator function.
# Ruby code
page.select('p').min('shortestParagraphLength') do |value, index|
page << 'value.innerHTML.length'
end
// Generated JavaScript
var shortestParagraphLength = $$("p").min(function(value, index) {
return value.innerHTML.length;
});
partition(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function and is executed once for each element. The JavaScript variable is set to an Array containing to Arrays. The first Array contains all of the elements for which the iterator function evaluated to true. The second Array contains all of the remaining elements.
# Ruby code
page.select('.products').partition('productsByVisibility') do |value, index|
value.visible
end
// Generated JavaScript
var productsByVisibility = $$(".products").partition(function(value, index) {
return value.visible();
});
pluck(variable, property)
Iterates through the collection creating a new Array from the value of the given property of each object without a function call. The resulting Array is assigned to the JavaScript variable.
# Ruby code
page.select('.amounts').pluck('amounts', 'innerHTML')
// Generated JavaScript
var amounts = $$(".amounts").pluck("innerHTML");
reject(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. The JavaScript variable is assigned to an Array of all elements for which the iterator function returns false.
# Ruby code
page.select('p').reject('paragraphsWithContent') do |value, index|
value.empty
end
// Generated JavaScript
var paragraphsWithContent = $$("p").reject(function(value, index) {
return value.empty();
});
select(variable){|value, index| block }
A synonym for JavaScriptCollectionProxy#find_all().
sort_by(variable){|value, index| block }
Each element is passed to the given block. The block is converted to a JavaScript iterator function. Assigns the JavaScript variable to an Array of the elements sorted using the result of the iterator function as keys for the comparisons when sorting.
# Ruby code
page.select('p').sort_by('sortedParagraphs') do |value, index|
page << 'value.innerHTML.length;'
end
// Generated JavaScript
var sortedParagraphs = $$("p").sortBy(function(value, index) {
return value.innerHTML.length;
});
zip(variable, arg1, ...){|value, index| block }
Merges elements with the arrays passed as parameters. Elements in the corresponding index of each array form a new array. The resulting array of arrays is assigned to the JavaScript variable. If a block is provided it is converted to an iterator function and is applied to each resulting Array. The name of the parameter to the iterator function is array.
For this example, assume that the page has the following paragraph elements:
First Paragraph
Second Paragraph
First, applying zip without a block:
# Ruby code
page.select('p').zip('zipped', [1, 2], [3,4])
// Generated JavaScript
var zipped = $$('p').zip([1,2], [3,4]);
The resulting array of arrays, where the paragraphs (represented by their ids) are DOM objects:
[[< id="first">, 1, 3], [
, 2, 4]]
Applying zip with a block:
# Ruby code
page.select('p').zip('zipped', [1, 2], [3,4]) do |array|
page.call 'array.reverse'
end
// Generated JavaScript
var zipped = $$("p").zip([1,2], [3,4], function(array) {
return array.reverse();
});
The resulting Array of arrays, where the paragraphs (represented by their ids) are DOM objects:
[[3, 1,
], [4, 2,
]]
Visual Effects
For the purposes of RJS templates, all visual effects are accessed using the name of the effect as a symbol, e.g., :highlight for the Highlight effect. The chosen effect is passed to JavaScriptGenerator#visual_effect(). The effect name is converted to camel-case. So for example, so if a new effect was added to Scriptaculous named FizzleOut, you would access it from RJS using its underscored name fizzle_out. Following is a list of the current effects shipping with the Scriptaculous library as of Rails 1.1:
appear
Element gradually appears.
blind_down
Causes the div element specified to slowly slide down into visibility like a blind being pulled down.
blind_up
The opposite of blind_down. Causes the element to slowly slide up and out of view like a blind being drawn up.
drop_out
Causes the element to drop down out of view.
fade
The opposite of appear. The element gradually fades from view.
fold
First blinds up the element about 90% of the way and then squishes it over to the left side of the region it originally occupied.
grow
Element grows up and into view from the bottom of the area occupied by the element.
highlight
Perform the "Yellow Fade Technique" on the element.
puff
The element expands and becomes transparent until it disappears.
pulsate
Make the element flash on and off.
shake
Causes the element to shake back and forth horizontally. Great for drawing the user's attention.
shrink
The opposite of grow. The element shrinks away off of the screen toward the bottom of the area it occupies.
slide_down
Causes the entire element to slide down into view.
slide_up
The opposite of slide_down. Causes the element to slide up and out of view.
squish
Squishes the element out of view by quickly compressing it into the upper left hand corner of the space it occupies.
switch_off
Causes the element to flicker and the drops out of view, similar to drop_out.
toggle_appear
Toggles the element between being visible and hidden. Uses appear when making the element visible and fade when hiding the element.
toggle_blind
The same as toggle_appear, but uses blind_down and blind_up for showing and hiding the elements respectively.
toggle_slide
The same as toggle_appear, but uses slide_down and slide_up for showing and hiding the elements respectively.