[size=xx-large][color=indigo]JavaScriptGenerator[/color][/size]

摘自:《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 codepage.insert_html(:bottom, 'products', '<li>Refrigerator</li>')

// Generated JavaScriptnew Insertion.Bottom("products", "<li>Refrigerator</li>");

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  <li>  tag can be rendered instead of having to replace the innerHTML of the  <li> . Replacing just the innerHTML would require the  <li>  tag to be moved out of the partial.

        # Ruby code        product.replace 'banner', '<id="banner">Welcome back Cody</div>'

        // Generated JavaScript        Element.replace("banner", "<id=\"banner\">Welcome back Cody</div>");

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});

[size=x-large][color=darkred]JavaScriptElementProxy[/color][/size]



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'

[size=xx-large][color=darkblue]JavaScriptCollectionProxy[/color][/size]

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 methodsJavaScriptGenerator#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 codepage.select('#elements span').all('allVisible') do |element, index|  element.visibleend

// Generated JavaScriptvar 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 EnumerationsThe 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 ReferenceAll 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  <div>  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:

        <p id="first">First Paragraph</p>        <p id="second">Second Paragraph</p>

        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], [<p id="second" >, 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, <p id="first">], [4, 2, <p id="second" >]]

[size=x-large][color=greens]Visual Effects[/color][/size]

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.

RJS Reference相关推荐

  1. undefined reference to 'pthread_create'问题解决(转)

    undefined reference to 'pthread_create' undefined reference to 'pthread_join' 问题原因:     pthread 库不是 ...

  2. 《Java: The Complete Reference》等书读书笔记

    春节期间读了下<Java: The Complete Reference>发现这本书写的深入浅出,我想一个问题,书中很多内容我们也知道,但是为什么我们就写不出这样一本书,这么全面,这么系统 ...

  3. undefined reference to `libiconv_open 无法编译PHP libiconv

    原文:http://hi.baidu.com/ostech/blog/item/a63f9b0dabed1ae7ab6457d0.html ./configure --with-mysql=/back ...

  4. 【Qt】error: undefined reference to `vtable for MainWindow‘

    1.问题描述 在写一个demo时,想尽量简单,就把MainWindow类的定义和实现都写在main.cpp中,结果编译时报错: main.cpp:-1: error: undefined refere ...

  5. 【Qt】报错error: undefined reference to `vtable for的解决方法

    1.问题描述 编译Qt程序时,在某个类构造函数定义处报错: error: undefined reference to `vtable for 2.原因分析 导致错误信息的原因是:子类没有实现父类的纯 ...

  6. 【ffmpeg】编译时报错:error: undefined reference to `av...

    1.问题描述 昨天使用ffmpeg库编译demo一切正常,今天再次链接ffmpeg库时报了一堆错误: error: undefined reference to `av_frame_alloc()' ...

  7. undefined reference to android log print,undefined reference to '__android_log_print'

    场景:undefined reference to `android_log_print' undefined reference to `__android_log_print' 原因:没有加入支持 ...

  8. C++中Reference与指针(Pointer)的使用对比

    了解引用reference与指针pointer到底有什么不同可以帮助你决定什么时候该用reference,什么时候该用pointer. 在C++ 中,reference在很多方面与指针(pointer ...

  9. c++中的对象引用(object reference)与对象指针的区别

    2019独角兽企业重金招聘Python工程师标准>>> ★ 相同点: 1. 都是地址的概念: 指针指向一块内存,它的内容是所指内存的地址:引用是某块内存的别名. ★ 区别: 1. 指 ...

最新文章

  1. 亿级流量架构之分布式事务思路及方法
  2. 潘建伟团队再次展示量子计算优越性!“祖冲之号”1.2小时就能完成超算8年计算量...
  3. java jdk下载过慢 解决方案
  4. 成功解决启动SQLServer失败,根据错误信息判断错误故障
  5. 笨小猴pascal题解
  6. python交互式shell_交互式 shell 玩转 Python
  7. JavaScript从入门到精通之入门篇(一)概念与语法
  8. 基于R树索引的点面关系判断以及效率优化统计
  9. 雷军谈小米10售价:不贵,交个朋友;百度开源首个口罩人脸检测模型;优麒麟18.04.4 LTS发布 | 极客头条...
  10. 深入浅出MyBatis:MyBatis解析和运行原理
  11. sony电视遥控器android,划重点!如何用手机当“点播遥控器”?
  12. 学UI设计出来可以从事什么工作?
  13. “为什么要选择Startups?”--GitCafe邀您回顾第一期企业联合招聘
  14. treeGrid插件
  15. WICC | 风口之下,音视频社交出海的三大新机遇
  16. flashback六大技术之flashback drop
  17. git command
  18. 忽视这5件事,2年后你将连手机都看不清了!附恢复视力方法
  19. 【react native】Flatlist实现上拉滚动加载
  20. python默认安装目录在哪_怎么查看python的安装目录

热门文章

  1. 精英科技GearReleases视频培训,以帮助​​客户避免损坏他们的触摸屏
  2. Kvm与webvirtmgr虚拟化安装
  3. 统计学第四周-概率分布
  4. FI凭证冲销(蓝冲、红冲)和反记账后台配置
  5. HotFix移动热修复详解
  6. Windows MFC 工程应用开发与框架原理完全剖析教程(下)
  7. Linux驱动编程 step-by-step (二)
  8. 无法对多重选择区域执行此操作
  9. 如何用 IT 业者能听懂的话介绍量子计算的原理?
  10. “科林明伦杯”哈尔滨理工大学第十届程序设计竞赛