1

i have an jscript object. I insert some html in a div, and i try to attach an event click to an html label, all insede the object, by how can access methods and properties of object inside jquery click event function?

HTML code:

<div id="content"></div>

JAVASCRIPT code:

<SCRIPT ...
jQuery().ready(function (){
    obj=new myobject("myobject1","#content"); //create object instance
    obj.dohtml(); //call method dohtml
});

//object I pass an objectname and a id from an html element 
function myobject(objectname,htmlid){

    this.name=objectname; //name of object 
    this.htmlid=htmlid;   //id where i try to create some html

    //say hello
    this.hello=function(){
       alert(hello); 
    }

    //do something with html
    this.dohtml=function(){

    //create an <p> element in a the html with id=htmlid 
    $(this.htmlid).html('<p id="'+this.name+'_myp" > my text </p>')     

    //click event on <p> id= this.name+'_myp"
    $("#"+this.name+'_myp').click(function(){
        alert(this.name); //i try to access property this.name in the object and dont work
        //how can access to this property from here

        this.hello(); //how can access to this method from here

    });

    $("#"+this.name+'_myp').click(this.hello()); //this dont work too why?

 } 

}

1 Answer 1

2

your scope changes inside the click callback.. so you need to keep the this var stored:

var that = this;
$("#"+this.name+'_myp').click(function(){
    alert(that.name); //i try to access property this.name in the object and dont work
    that.hello(); //how can access to this method from here
}); 

For the second part:

you're executing the function and passing the return value when you do this.hello(), if you just want to pass the function, you would pass this.hello with no ()

$("#"+this.name+'_myp').click(this.hello);

it works with this because you are still in scope.

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

1 Comment

you are right, sorry I a new with javascript. ¿is this the correct from to encapsulate my work?

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.