Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a javascript file abc.js. I have kept it inside app/assets/javascripts/abc folder.

In my application.js file, I have given

//= require abc/abc

In my view, I need to display the object that is returned by a function inside the abc.js file.

I am calling the function by the following command

%h4.sub-header Test Project

%textarea.form-control{rows: 10}

  :javascript

    abc.diff(@a, @b)

I am getting the a & b values from the controller.

But the function is not being called. Instead the sentence "abc.diff(a,b)" is being displayed.

Could anyone tell me how to call the function inside my view?

share|improve this question
    
Can you update your post to include your view code? –  steve klein 21 hours ago
    
I have updated my view code now. –  Sid 21 hours ago
    
You'll need to interpolate to evaluate @a and @b in Ruby before passing to js (abc.diff(#{@a}, #{@b})). –  steve klein 21 hours ago
    
My view file name is index.html.haml. Yes , I am using haml. I tried it with #{}. Now it s displaying like this.... abc.diff('...(JSON object1)....', '....(JSON object2)....') –  Sid 21 hours ago
    
I think this should work as long as you use interpolation and the line in question is indented two spaces more than :javascript. –  steve klein 21 hours ago

1 Answer 1

Inside haml javascript blocks you can just do string interpolation. Also indentation is very important in haml (obviously). So your view should look like:

%h4.sub-header Test Project
%textarea.form-control{rows: 10}

:javascript
  abc.diff(#{@a}, #{@b});

Without more info it is hard to say more, but in general this is not the preferred way: your code should be precompiled in javascript assets, and generally I define variable or add data attributes to specific items.

So either something like

:javascript
  var a = #{@a};
  var b = #{@b};

ad inside abs.js.coffee write

$ -> 
   abc.diff(a,b)

The cleanest solution imho is something like:

%body{'data-a': @a, 'data-b': @b}

and inside abs.js.coffee write

$ -> 
  a = $('body').data('a')
  b = $('body'_.data('b')
  abs.diff(a,b)

Of course, this depends whether it applies to your solution, my apologies for digressing :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.