I would like to know how to reuse an event handler that is in an external js file that I can't change
If there are other ways to reuse event handlers, please let me know as well.
Not sure how to fix it
I am getting the below error and I don't know how to solve it.
Uncaught ReferenceError: show is not defined
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<ul class="flex gap-5 mb-5 [&_a]:underline [&_a:hover]:no-underline">
<li><a href="#" class="org text-indigo-500 ">CLICK ORG</a></li>
<li><a href="#" class="copy text-red-500 ">CLICK COPY</a></li>
</ul>
<div class="baz">BAZ</div>
<!--
external js file that I cannot change.
<script src="external.js"></script>
-->
<script>
//Contents of external.js
jQuery(function($) {
init();
function init() {
$('a').on('click', function(event){
var foo = $('.baz').text();
var bar = 'BAR';
show({
'one': foo,
'two': bar,
});
event.preventDefault();
});
}
function show(obj) {
console.log(obj.one);
console.log(obj.two);
}
});
</script>
<script>
jQuery(function($) {
const handler = $._data($('.org').get(0), "events")['click'][0]['handler'];
const strFun = handler.toString();
const funcFromStr = new Function('return ' + strFun.replace("$('.baz').text()", "'FOO'"))();
$('.copy').on('click', function(event){
funcFromStr();
event.preventDefault();
});
});
</script>
Reference information
const handler = $._data($('.org').get(0), "events")['click'][0]['handler'];
const strFunBody = strFun.substring(strFun.indexOf("{") + 1, strFun.lastIndexOf("}")).replace("'FOO'", "$('.baz').text()");
- d3.js - Deep clone a function in javascript - Stack Overflow
- ecmascript 6 - Making a true copy of a function in Javascript - Stack Overflow
const funcFromStr = new Function('return ' + strFun.replace("'FOO'", "$('.baz').text()"))();
When using javascript instead of jQuery
- javascript - How to Get Event Listener of an Element - Stack Overflow
- Javascript - How to list all active event listeners on a Web page
Contents of the past
Change Title
- Previous Title
How to avoid errors when using The "new Function" syntax to reuse event handlers(Uncaught SyntaxError: Unexpected token 'function')
Change Body
I would like to know how to avoid errors when using The "new Function" syntax to reuse event handlers.(Uncaught SyntaxError: Unexpected token 'function')