0

if I have a jquery namespace like so:

 var sc = {
          calcResult: function(){
                 //do stuff
                },
           initialise: function () {
              $('#myid').click(function(){
               //would like to call calcResult() here
              }
           }

How do I call calcResult from within the initialise function? I tried this.calcResult() and sc.calcResult() but both complain with undefined error.

2 Answers 2

1

Did you also call the sc.initialise() somewhere to bind the click event handler? In the snippet below it works with sc.calcResult()

var sc = {
  calcResult: function() {
    //do stuff
    alert("Do stuff");
  },
  initialise: function() {
    $('#myid').click(function() {
      //would like to call calcResult() here
      sc.calcResult();
    });
  }
}

sc.initialise();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myid">Click</button>

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

1 Comment

I must have had a typo or something because now that I've reinstated the code, it's working. thanks.
1

sc object looks like a standalone object (calcResult belong to that particular object and not to some specific constructor function prototype). So you need to point to the sc object itself so you can use the calcResult (function) property. Then, you have two options:

create a reference to the appropriate this object in initialise function scope:

initialise: function () {
    var that = this;
    $('#myid').click(function(){
        // "that" variable points to the right reference
        // the object that sc points to
        that.calcResult()
    });
}

You could also use the sc variable directly

var sc = {
    calcResult: function(){
    },
    initialise: function () {
        $('#myid').click(function(){
            sc.calcResult()
        });
    }
};

But depending on what you try to achieve, you may prefer one solution over the other.

If you have similar object like sc having the same functions as direct properties, you should probably create a constructor so that properties functions belong to the constructor prototype instead of copying every function onto every particular "instance" object.

Comments

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.