1

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

4
  • 1
    The real question is, why on earth would you put an event handler inside a function like that at all, you generally don't want to attach multiple click events to the same element anyway, and even stranger is the DOM ready handler. I think you're simply just doing this wrong. Commented Jun 25, 2015 at 16:38
  • @adeneo, what he probably actually wants is to store $("#myTarget").html(this.word) as a method & bind it to DOM on load.. Anyway, that's the only explanation that makes sense that I see.. Commented Jun 25, 2015 at 16:44
  • Sounds like an XY Problem Commented Jun 25, 2015 at 16:45
  • @adeneo I'm new to OOP and jQuery, and obviously, I'm wrong. I just want to know how to this or just if it is possible. Tyblitz understood what I wanted to do. Perhaps, my question was unclear. Commented Jun 25, 2015 at 16:54

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.