John Stoner
John Stoner

Reputation: 105

Calling a Javascript function back in the web page from a .js library

I'm pretty new to Javascript, so take that for what it's worth.

So, I have three validation paths in my code. The paths occur on different pages. My thought was to put the validation code in the pages, and invoke and act on them from an included library. On the pages they'd all have the same namespace name and function name, thus giving me some nice polymorphism.

Thus, in a.html:

<script>
if(typeof INSTANTFEEDBACKVALIDATE === "undefined") { INSTANTFEEDBACKVALIDATE = {}; }
</script>
<script type="text/javascript" language="javascript" src="/static/js/b.js"></script>
...
$(document).ready(function(){
$('.submit-request').click(function(e){
    e.preventDefault();

    INSTANTFEEDBACK.do_stuff();
    $('#myform').submit();
}
})

then in b.js:

(function(){

INSTANTFEEDBACK.do_stuff = function(){
    if(INSTANTFEEDBACKVALIDATE.validate()){
        do_shared_valid_stuff();
    } else {
        do_shared_invalid_stuff();
    }
}
})

then back in a.html:

(function(){

INSTANTFEEDBACKVALIDATE.validate = function(){

    // validation code
}
})

where I run into trouble is on the way back--on the call to INSTANTFEEDBACKVALIDATE.validate() it's not finding the INSTANTFEEDBACKVALIDATE global. Or at least that's how I interpret this message:

Uncaught TypeError: Object #<Object> has no method 'validate' 

Anyone got any ideas? Or maybe a better way to do this?

Upvotes: 0

Views: 55

Answers (1)

Chris Peacock
Chris Peacock

Reputation: 4686

In a.html, you need to invoke your function like so:

   (function(){

        INSTANTFEEDBACKVALIDATE.validate = function(){

        // validation code
        }
    })();

Note the '();' at the end. Without this, you're just declaring the function but not invoking it.

Upvotes: 1

Related Questions