The function is like:
(function ($) {
$(document).ready(function () {
var MyObject = {
MyFunction: function(){
alert('I am here');
}
}
});
}(jQuery));
MyObject.MyFunction();
How can I call it like above?
The function is like:
(function ($) {
$(document).ready(function () {
var MyObject = {
MyFunction: function(){
alert('I am here');
}
}
});
}(jQuery));
MyObject.MyFunction();
How can I call it like above?
document.ready()
callbacks are called in the order they were registered (ref). One way to achieve your goal is to create a global object, then initialize it in one $(document).ready()
and call it in a subsequent $(document).ready()
.
var MyObject = {};
(function($) {
$(document).ready(function() {
MyObject = {
MyFunction: function() {
alert('I am here');
}
}
});
}(jQuery));
(function($) {
$(document).ready(function() {
MyObject.MyFunction();
});
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You variable loses scope outside the event where you are declaring it.
Your code
(function ($) {
$(document).ready(function () {
var MyObject = {
MyFunction: function(){
alert('I am here');
}
}
});
}(jQuery));
your declaration and outside any other scope defined by some other function that's scope not accessible by your function call
var MyObject
needs to be outside $(document).ready(...)
So, you are after option 1.
// Option 1: Object in a gloabl scrope
var myObject = {
myFunction: function(){
alert('I am here');
}
};
(function ($) {
// Option 2: Object in a function scope
var myObject2 = {
myFunction2: function(){
alert('I am here 2');
}
};
$(document).ready(function () {
// Option 3: Object in a local (to the "(function ($) {") function scope
var myObject3 = {
myFunction3: function(){
alert('I am here 3');
}
};
//alerts 'I am here 2';
myObject2.myFunction2();
//alerts 'I am here 3';
myObject3.myFunction3();
});
//alerts 'I am here 2';
myObject2.myFunction2();
//Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
myObject3.myFunction3();
}(jQuery));
//alerts 'I am here';
myObject.myFunction();
//Uncaught TypeError: myObject2.myFunction2 is not a function - can't access a locally scoped function on a global scope
myObject2.myFunction2();
//Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
myObject3.myFunction3();