Call javascript function onclick in Rails

前端 未结 2 1307
Happy的楠姐
Happy的楠姐 2021-02-08 18:26

I have the following code in one of my views:


And, the .js.

2条回答
  •  长情又很酷
    2021-02-08 19:02

    I am new to web development

    Since you're new, let me give you some ideas on how to improve your code:


    Unobtrusive JS (UJS)

    This tutorial explains it very well

    Rails convention is geared towards "unobtrusive" javascript functionality. This means you can assign events to elements on your page without having to reference those elements directly (don't use inline onclick etc)

    This is best described in the same way as CSS - using inline CSS is ridiculously laborious & seen as bad practice (it's not DRY). A much better way is to have a central stylesheet, which you can then use to style elements on the page.

    Unobtrusive Javascript works in the same way - keep everything in files you call at runtime:

    #app/assets/javascripts/application.js
    $(".element").on("click", function(){
        ...
    });
    

    The importance of this cannot be stated enough - having unobtrusive JS is one of the best programming patterns you can apply; it not only DRIES up your code, but also ensures future development can be kept modular (a gold standard in development)


    Ajax

    Since you're using ajax, you may wish to use the Rails UJS Ajax functionality, which basically means this:

    <%= button_to "Analyze", analytics_api_path, id: "analyze", remote: true %>
    

    The remote: true option of this calls the Rails UJS driver's ajax functionality - basically setting up an ajax call without you having to write any code. The caveats of this are that you need to handle your own ajax:success process, and you'll need to point the element to the correct href

    I would do this:

    #app/assets/javascripts/application.js.coffee
    $("#analyze").on "ajax:success", (data, status, xhr) ->
        Analytics.doAnalysis data
    

提交回复
热议问题