I'm trying to understand how to call an object's method from HTML without declaring this object a global variable. Is it even possible? I don't really want to pollute the global scope, so I assume there must be a way to avoid this...
Let's say I have a javascript object which one of it's methods is called clearSelection(). This clearSelection() method just erases an html input text value and does some other stuff which isn't relevant to this question at all.
The issue is that when I declare this object inside an $(function(){}); as a local variable to that function, I can't access it from the input's onclick html attribute, as it's not defined.
My solution for this would be to declare this object as a global variable, maybe not right inside the window object but something less harmful like inside window.document.body (I believe it is worse to let it be declared right inside the window object, so I guess this is still bad...)
Here's some code for you:
My object:
function MyObject(foo,bar){
...
...
this.clearSelection() = function(){
// do some useful stuff here
...
}
}
Script tags inside my html:
<script>
$(function(){
var myObject = new MyObject(baz,bal);
});
</script>
My button declatarion @ html:
<button type="button" onclick="myObject.clearSelection()">Clear</button>
So, javascript console complains because myObject is not defined, and I assume it's due to the scope, because from the HTML I can't access the same scope that the object (myObject) lives in.
Current approach
This is how I'm doing it so it works, but I don't really like it and I'm asking for another cleaner way. The object structure and html button are the same so I'll skip those:
<script>
$(function(){
window.document.body.myObject = new MyObject(baz,bal);
});
</script>
window.myObject = ..., but best to move the event handling to your script, as @Satpal posted.