javascript - using jquery click eveny from within an object -
i want add click event <span>
in dom click event sits in object
i have html
<html> <body> <span id="metolog">hello-world </span> </body> <script> function makeobj(){ this.logme= $("#metolog").click(function(){ console.log("shoot") }) } const obj = new makeobj() obj.logme // want listen click event </script> </html>
as mentioned in comment problem you're storing in constructor's property logme
. click()
method returns jquery object, span in case, click handler never attached it.
what have right in constructor this:
function makeobj(){ this.logme= $("#metolog").click(function(){ console.log("shoot") }) } const myobj = new makeobj(); // test logme console.log(myobj.logme); // returns jquery object [span#metolog]
one solution transform logme
property method in order attach click handler element:
function makeobj(){ this.logme= function(){ $("#metolog").click(function(){ console.log("shoot") }); } } // create new instance const myobj = new makeobj(); // attach click handler myobj.logme(); // click on span , log should there
this sample seems you're after:
https://jsfiddle.net/ndkzjdyb/
i forgot mention since functions first class objects in javascript, can pass id string , specific handler constructor method make more dynamic. check revision of fiddle:
https://jsfiddle.net/ndkzjdyb/2/
edit
based on @dfsq's comment updated fiddles avoid adding more 1 event handler if method ran more once:
static method
https://jsfiddle.net/ndkzjdyb/3/
Comments
Post a Comment