How to create dynamic javascript with Ruby On Rails?

两盒软妹~` 提交于 2019-12-25 04:09:35

问题


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>
...

回答1:


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.




回答2:


Maybe it's easier to do this entirely in Javascript:

Add a class to all calendar elements:

<div id="player1_calendar" class="player-calendar"></div>

Then iterate over all of them and attach your fullCalendar:

$('.player-calendar').each(function(idx, calendar) {
    $(calendar).fullCalendar({});
});


来源:https://stackoverflow.com/questions/28506994/how-to-create-dynamic-javascript-with-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!