Reputation: 2053
I can't for the life of me figure out how to do this. I have my jquery name spaced a certain way in that it is prefixed with NWO.{function-name} to make it a little more organized. So it looks something like this:
var NWO = NWO || {}
NWO.Chat = (function() {
return{
init : function($objects) {
console.log('do something');
} }
}
}());
jQuery(document).ready(function(){
NWO.Chat.init($('div').find('a.chat'));
});
Now the chat element isn't on every page so on certain pages where the chat link doesn't exist I get a NWO.Chat is undefined. I thought for the pages that don't have the chat link I could do something like this to avoid the error.
if(jQuery().NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }
or
if($.fn.NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }
But neither seems to be working I still get the error. How do I avoid the js error when the chat link isn't on the page. I've been banging my head for hours. Thanks in advance.
Upvotes: 0
Views: 113
Reputation: 148140
You can use typeof to check if the object is defined or not by comparing it with "undefined"
if(typeof NWO.Chat != 'undefined')
Upvotes: 1
Reputation: 7668
You can also just fix the root of your problem:
NWO.Chat = (function() {
return{
init : function($objects) {
console.log('do something');
} }
} // <<-----------REMOVE THIS CURLY BRACE
}());
That extra curly at the end (}
) is the issue.
Upvotes: 0
Reputation: 388316
NWO
is not a jQuery plugin so have nothing to do with jQuery, it is a object(looks like a global scope), so you could just do
if (NWO && NWO.Chat && typeof NWO.Chat.init == 'function') {
NWO.Chat.init($('div').find('a.chat'));
}
Upvotes: 5