Ad

Changing Object's Property Value With Method

- 1 answer

I'm kind of new to both JavaScript and jQuery but got some programming experience on other languages. This is what I wrote:

var pageFunctionality = {
    value: 0,
    onUpdate: function () {
        $("#numberOfTimes").html(pageFunctionality.value);
        console.log(pageFunctionality.value + "!");
    },
    onBtnClick: function () {
        this.value++;
        console.log(this.value);
        pageFunctionality.onUpdate();
    }
};
$(document).ready(function () {
    $("#btn").click(pageFunctionality.onBtnClick);
});

The problem is this: when I log the "value" inside the "onBtnClick", it clearly increases, but then, when I log it inside the onUpdate method, it keep being 0.

This is the output it produces:

1
0!
2
0!
3
0!
4
0!

I hope you can help me.

Ad

Answer

You have an issue with the value of this in your onBtnClick() handler because of the way it is being called from the .click() handler. By default, jQuery will set this to be the DOM element that you hooked the event handler to.

If you don't need access to that DOM element in the click handler, then you can change your code to this:

$(document).ready(function () {
    $("#btn").click(pageFunctionality.onBtnClick.bind(pageFunctionality));
});

Using .bind() like this will override the value of this to be what you want it to be.


Or, since pageFunctionality is a singleton, you could just stop using this inside the event handler and refer directly to pageFunctionality like this:

var pageFunctionality = {
    value: 0,
    onUpdate: function () {
        $("#numberOfTimes").html(pageFunctionality.value);
        console.log(pageFunctionality.value + "!");
    },
    onBtnClick: function () {
        pageFunctionality.value++;
        console.log(pageFunctionality.value);
        pageFunctionality.onUpdate();
    }
};
$(document).ready(function () {
    $("#btn").click(pageFunctionality.onBtnClick);
});
Ad
source: stackoverflow.com
Ad