Reputation: 29
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
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
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