Reputation: 1164
In the form
object below, from within the "check" function, how do I call the "show" and "hide" methods of the notification function?
(function (namespace, $, undefined) {
var form = {
check : function(){
form.notification.show(); // Generates an error
},
notification : function(){
this.show = function(){
...
};
this.hide = function(){
...
};
}
};
}(window.namespace = window.namespace || {}, jQuery));
With form.notification.show()
I get the following error:
Uncaught TypeError: Cannot read property 'show' of undefined
Upvotes: 0
Views: 56
Reputation: 328556
Try to define notification
outside form
and then refer to it:
var notification : { // no function here
show : function(){...}, // avoid "this"
hide : function(){...}
};
var form = {
check : function(){
notification.show(); // <-- Use here
},
notification : notification // and here
};
(I omitted the jQuery
protection code for clarity).
The next problem is that you this.show =
will assign the function to whatever this
is when the function notification()
is executed. this
isn't notification
!
Upvotes: 1
Reputation: 1033
You've enclosed it, so you need to return it and that will expose it for you, if you whip the following in chrome console, you'll see you have access to the form object
(function (namespace, $, undefined) {
var form = {
check : function(){
form.notification.show(); // Generates an error
},
notification : function(){
this.show = function(){
};
this.hide = function(){
};
}
};
return{form:form};}(window.namespace = window.namespace || {}, jQuery));
All i've done to your code is added
return{form:form};
After the form object. Hope this helps
EDIT
If you want to only expose certain parts of the form, for example only notifications, you could modify the return like so:
return{form.notification: notification}
Upvotes: 0