Lost in javascript scope
could someone please help me out with the (simplified) code below. I'm trying to call the doTheSlide()
function from within the slide event function. I'm still a tad shady on my understanding of scope in JS.
What is a correct way to achieve this? I'm getting this error: 开发者_开发技巧
Uncaught TypeError: object is not a function
(function($) {
bindEvent = function(slider) {
slider.bind('slide', function(event, ui) {
doTheSlide(ui.value);
});
}
doTheSlide = function(value) {
//Animate the slide
}
var methods
})(jQuery);
You need to declare 'doTheSlide' somewhere. You seem to be using it as a global function, which is wrong most of the time. Make sure that everything is declared properly (with var or using a named function).
Here is a fixed version of your code (the way I prefer it):
(function($) {
function doTheSlide(value) {
//Animate the slide
}
function bindEvent(slider) {
slider.bind('slide', function(event, ui) {
doTheSlide(ui.value);
});
}
})(jQuery);
Remember to declare functions before they are used. It will work to call a function that is declared later, but it is not good style.
Alternative syntax:
(function($) {
var doTheSlide = function(value) {
//Animate the slide
};
var bindEvent = function(slider) {
slider.bind('slide', function(event, ui) {
doTheSlide(ui.value);
});
};
})(jQuery);
精彩评论