问题
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