如何使用Ruby On Rails创建动态JavaScript? [英] How to create dynamic javascript with Ruby On Rails?

查看:100
本文介绍了如何使用Ruby On Rails创建动态JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验jQuery FullCalendar 和Ruby On Rails,
我有一个叫做模型的模型播放器。我想为每个玩家在索引模板上呈现日历。

  $('#player1_calendar')。fullCalendar({ b $ b //将您的选项和回调放在这里
})

渲染日历在视图中





我该如何动态地为每个玩家添加一个日历,以便我可以调用它来渲染它:

 < div id =player1_calendar>< / div> 
< div id =player2_calendar>< / div>
< div id =player3_calendar>< / div>
...


解决方案

不同的是。

问题是,Rails能够以JSON返回数据,这是一种JavaScript本地数据格式。也就是说,您可以编写静态JS并为其添加一个动态JSON数据端点。



一般算法如下:


  • 添加一个JSON端点,它提供了在每个特定情况下决定选项所需的所有数据:这可能是一个端点,它返回给定页面上所有球员的数据

  • 在HTML中,使用something突出显示集合的根标签:用于行为相关的选项我使用 data - 属性;您甚至可以在属性值中提供端点的URL:关键是,您应该能够设计一个选择器来查找这些

  • 编写静态JavaScript,可以通过选择器查找所有标记设计如上,查询所需数据,然后使用接收到的数据用正确的选项调用 fullCalendar


这是消除对动态JavaScript需求的一般方法。对于单点解决方案来说,这显然是矫枉过正的,但对于频繁使用,这更方便,因为它允许您应用您的行为而不生成纯JS或甚至将JS插入到页面中,但只能由DOM触发。

b $ b

I'm experimenting with jQuery FullCalendar and Ruby On Rails, I have a model called Player. I want to render a calendar for each player on the index template.

$('#player1_calendar').fullCalendar({
        // put your options and callbacks here
})

To render de calendar on the view

how can I can dynamically add a calendar to each player so I can call render it like:

<div id="player1_calendar"></div>
<div id="player2_calendar"></div>
<div id="player3_calendar"></div>
...

解决方案

I would approach this differently.

The thing is, Rails is well able of returning data in JSON, which is a native data format for JavaScript. That said, you can write static JS and add a dynamic JSON data endpoint to it.

The general algorithm is as follows:

  • Add a JSON endpoint that provides all the data necessary for deciding on the options in every specific case: this may be an endpoint returning the data for all the players on the given page
  • In HTML highlight the root tag of the collection with something: for behavior-related options I use data-attributes; you may even provide the URL for the endpoint in attribute value: the point is, you should be able to design a selector to find these
  • Write static JavaScript that finds all the tags by the selector designed above, queries for the required data, then uses the received data to call fullCalendar with the correct options

This is a general way to eliminate the need for dynamic JavaScript. For single-place solutions it's obviously overkill, but for frequent usage this is more convenient, as it allows you to apply your behavior without generating plain JS or even inserting JS into the page, yet only triggered by the DOM.

这篇关于如何使用Ruby On Rails创建动态JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆