Pass a ruby variable into js within Rails

35 views
Skip to first unread message

Pierre-Andre M.

unread,
May 29, 2014, 5:39:11 PM5/29/14
to rubyonra...@googlegroups.com
I have a variable created by some ruby in my controller that looks like
this:

@begpoint = row["begpoint"]


and I want to pass it into some js that is referenced from within my
view:

view:

<% javascript_include_tag "play_time" %>



js (play_time):

I am trying to pass "<beg-point> into the js [obviously that <> is not
the right syntax just trying to denote where'd id like the variable to
end up]


var endtime = <beg-point>+10;
myPlayer= document.getElementById('example_video_1');
myPlayer.addEventListener('loadeddata', function(){
myPlayer.currentTime = 10505.89;
myPlayer.play();
myPlayer.addEventListener('timeupdate', function(){
if (myPlayer.currentTime >= endtime) {
myPlayer.pause();
}


Can anyone help? Thanks

}, false);

}, false);

--
Posted via http://www.ruby-forum.com/.

Robert Walker

unread,
May 29, 2014, 7:45:04 PM5/29/14
to rubyonra...@googlegroups.com
Pierre-Andre M. wrote in post #1147586:
> I have a variable created by some ruby in my controller that looks like
> this:
>
> @begpoint = row["begpoint"]
>
>
> and I want to pass it into some js that is referenced from within my
> view:

There are several way of doing this, but the simplest is to use HTML5
data- attributes.

Example:

HTML:

<body data-begpoint="<%= @begpoint %>">
... page content
</body>

jQuery:

var begpoint;

$(funtion() {
begpoint = $('body').data('begpoint');
});

So to think of is as "pass it to JavaScript" is sort of inside out. You
use JavaScript to "get" the value from the DOM. jQuery gives you nice
syntax for doing just that.

This is good for relatively small amount of data. If you need lots of
data in your JavaScript there are alternatives to this technique. A good
place to learn something about those techniques is something like
Backbone.js, Ember.js or Angular.

http://backbonejs.org
http://emberjs.com
https://angularjs.org

Dave Sims

unread,
May 29, 2014, 7:46:13 PM5/29/14
to rubyonra...@googlegroups.com
I've used the gon gem for this and liked it quite a bit.

https://github.com/gazay/gon

greatghoul

unread,
May 29, 2014, 10:54:59 PM5/29/14
to rubyonra...@googlegroups.com
gon is great, and easy to use.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/5387C680.30601%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


--
 greatghoul - Ask and Learn!

Reply all
Reply to author
Forward
0 new messages