Pass a ruby variable into js within Rails


#1

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 " 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 = +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);


#2

I’ve used the gon gem for this and liked it quite a bit.

https://github.com/gazay/gon


#3

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:

... page content

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


#4

gon is great, and easy to use.

On Friday, May 30, 2014, Dave S. removed_email_address@domain.invalid wrote:

@begpoint = row[“begpoint”]

 myPlayer.currentTime = 10505.89;

<javascript:_e(%7B%7D,‘cvml’,‘removed_email_address@domain.invalid’);>.
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/5387C680.30601%40gmail.com

https://groups.google.com/d/msgid/rubyonrails-talk/5387C680.30601%40gmail.com?utm_medium=email&utm_source=footer

.
For more options, visit https://groups.google.com/d/optout.


greatghoul http://www.g2w.me - Ask and Learn!