fuatkaraca fuatkaraca - 3 months ago 5
Javascript Question

How to change property of object by its own function?

This is from my own js file.

function hesap (hesapdiv, hesapmodal, hesapid){
this.hesapid = hesapid;
this.hesapdiv = hesapdiv;
this.hesapmodal = hesapmodal;

hesapdiv.on("click", "button", function() {
hesapmodal.modal("show");
});


hesapmodal.on("click", "button[hesapid]", function() {
var hesapid = $(this).attr('hesapid');
console.log(this.hesapid + "-" + hesapid + "-" + $(this).attr('hesapid'));
var isim = $(this).attr('isim');
hesapdiv.find("input").val(hesapid + " - " + isim);
hesapmodal.modal('hide');
});}


And the below code, i could use in all of my web pages.

var hesap1 = new hesap($("#hesapdiv"), $("#HesaplarModal"), 36);
$("#kasaislemikaydet").on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
alert(hesap1.hesapid);)};


Now, when user choose a 'hesap' from the modal, function is success for getting the values of attributes. But it does not assign the value to 'hesapid' of object. So from the web page i can't get the new value of hesapid. For example clicking on a button to get the value of new choosed 'hesapid', always alerts the first value '36'.

Answer
var _this=this; //save this to variable   

hesapmodal.on("click", "button[hesapid]", function() {

     console.log(_this.hesapid);//here You have object property and it can be changed
     //example assign
     _this.hesapid = $(this).attr('hesapid');

});

I am creating _this variable because this in callback of click event is DOM element on which event was called, so create reference for our this ( hesap object ) in _this variable which is visible in callback function and can be used there.

Full working code:

function hesap (hesapdiv, hesapmodal, hesapid){

    this.hesapid = hesapid;
    this.hesapdiv = hesapdiv;
    this.hesapmodal = hesapmodal;

    var _this=this;//to use this in click callback

    this.hesapdiv.on("click", "button", function() {

        _this.hesapmodal.modal("show");
    });


    this.hesapmodal.on("click", "button[hesapid]", function() {

        _this.hesapid = $(this).attr('hesapid');

        var isim = $(this).attr('isim');

        _this.hesapdiv.find("input").val( _this.hesapid + " - " + isim);

        _this.hesapmodal.modal('hide');

    });

}

Comments