Philip Dang
Philip Dang

Reputation: 29

How do I attach a jQuery event to a object's method?

I defined an object with properties and methods. But I can't find how to attach a jQuery function to a method. What I want is : when I click on the object #myTarget change its html text.

I wrote this :

function blockTest(word){
	this.word = ""+genRandInt(0, 25);	
	this.applyNewWord = function(){
		$(document).ready(function(){
			$("#myTarget").click(function(){
				$("#myTarget").html(this.word);		
			});
		});
	};
}

Actually, I'm trying to

Upvotes: 1

Views: 43

Answers (2)

Carl Edwards
Carl Edwards

Reputation: 14474

Accomplishing what you want based on the code you provided isn't the way to go. I'd first create an Object rather than using a function. Insert your attributes inside that object and handle your DOM events separately:

(function($) {
   var obj = {
     word: "Example Word",
     applyNewWord: function() {
       return this.word;
     }
   }
   
   $(function() {
     $("#myTarget").on("click", function() {
       $(this).text(obj.applyNewWord())
     });
   });
}(jQuery));
div {
  border: 1px solid black;
  cursor: pointer;
  padding: 5px;
}
<div id="myTarget">Dummy Text</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

function blockTest(word){
    var self = this;
    self.word = ""+genRandInt(0, 25);   
    self.applyNewWord = function(){

            $("#myTarget").click(function(){
                $(this).html(self.word);        
            });

    };
}

make copy of this and don't keep document.ready inside function

Upvotes: 0

Related Questions