Reputation: 32951
Here is my jquery code and it does not work. I really dont know why. Please help and also tell me how can I fix it.
$(function () {
var panel = function () {
var init = function () {
console.log('hello');
};
return {
init: init
}
};
$('.nav li a').on('click', function (e) {
panel.init();
});
})();
I am getting this error in my console
Object function () {
var panel = function () {
var init = function () {
console.log('hello');
}
};
return {
init: init
}
} has no method 'init'
Upvotes: 0
Views: 120
Reputation: 4559
In this case panel is a callback, and this callback return an other callback, init
, so you have to put () around both callback, try this:
$(function () {
var panel = function () {
var init = function () {
console.log('hello');
};
return {
init: init
}
};
$('.nav li a').on('click', function (e) {
panel().init();
});
})();
Upvotes: 0
Reputation: 318342
I would just do :
$(function () {
var panel = {
init: function () {
console.log('hello');
}
}
$('.nav li a').on('click', function (e) {
panel.init();
});
});
Seems more like what you're trying to do?
Upvotes: 0
Reputation: 9629
I'm guessing that panel should be using immediate invocation:
$(function () {
var panel = (function () {
var init = function () {
console.log('hello');
};
return {
init: init
}
})();
$('.nav li a').on('click', function (e) {
panel.init();
});
})();
The code will execute imeediately and return the object to the panel
variable. Hence panel
picks up an init
propertty.
Upvotes: 0
Reputation: 6500
Maybe you should take a look on how to define a class in Javascript:
http://www.phpied.com/3-ways-to-define-a-javascript-class/
var panel = {
init: function () {
alert("Hello!");
}
}
panel.init();
$('.nav li a').on('click', function (e) {
panel.init();
e.preventDefault();
});
Upvotes: 2
Reputation: 1508
Your init function is in another function panel. This is not reachable from outside. When you want to return the init method, then you have to put the init function a level higher if you know what I mean.
Upvotes: 0
Reputation: 6618
I think you are missing the parentheses off of the end of the panel function declaration.
var panel = function () {
var panel = function () {
var init = function () {
console.log('hello');
}
};
return {
init: init
}
}();
Make sure the closing brace is followed by ()
Upvotes: 0