IonTichy
IonTichy

Reputation: 435

Javascript-function-call in jquery event

I wrote a javascript class with a function called 'setVisibilityOfWeekdaySelectbox'. I create the object and call the function init(). This function contains the code below. When i call init(), the function 'setVisibilityOfWeekdaySelectbox' will be called. When i change the frequency-selectbox firebug says the function cannot be found.

    function ReportDefinition(options) {
        this.options = options;
    }

    ReportDefinition.prototype.init = function(){
       // change event of a select box
       $("#frequency").change(function(){
        this.setVisibilityOfWeekdaySelectbox();
        this.getReportTemplate().setFrequencyInformation();
       });

       this.getReportTemplate().setFrequencyInformation();
       this.setVisibilityOfWeekdaySelectbox();
    });

    ReportDefinition.prototype.setVisibilityOfWeekdaySelectbox = function (){
       if($("#frequency").val() === undefined){
        return;
       };

       if($("#frequency").val() === "WEEKLY"){
        $("#weekday_div").show();
       } else {
        $("#weekday_div").hide();
       }
   }

How do I have to change the class to make it work?

Upvotes: 0

Views: 35

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

this inside the event is not your object's instance, but the element itself.

Declare a var to instance your object(in a scope that it can be accessed by the event, e.g. globally, haha):

var report = new ReportDefinition();
report.init();

Then, inside the event, call it from the instance:

$("#frequency").change(function(){
    report.setVisibilityOfWeekdaySelectbox();
});

I don't know where in your code is getReportTemplate() but it may no work inside the event either. You have to fix its instance too.

Upvotes: 1

Related Questions