ruby on rails - What is the best way to rewrite a given code into a function in JavaScript? -


i need automatically rewrite link triggers function (written on fly) , convert unobtrusive javascript code.

example:

link_to_function 'hey', "alert('hey')" 

becomes:

<a href='#' onclick="alert('hey')"> hey </a> 

my idea make reference in html element , create object in js store related code. convert former example in cleaner , unobtrusive example:

<a href='#' data-href='rndreference'> hey </a> 

and in js (the code variable js code have stripped out markup):

storagecode[rndreference] = new function(code) 

each string of code passed through new function(code) in order call function.

what wrong in approach? approach better?

here’s normal way done.

<a href='#' onclick="alert('hey')"> hey </a> 

becomes:

<a href='#' data-role='alert'> hey </a> 

then in coffeescript file:

$ ->   $("a[data-role='alert']").on("click", (event) ->     event.preventdefault()     alert("hey")   ) 

or, if don’t coffeescript:

$(document).ready(function() {   $("a[data-role='alert']").on("click", function(event) {     event.preventdefault();     alert("hey");   }); ) 

Comments