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.

http://api.jquery.com/click/

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/

dynamic method

https://jsfiddle.net/ndkzjdyb/4/


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -