I have a basic jQuery plugin defined as such:
(function( $ ){
var new_row_num = 0;
// Test data for now
var courses = [
{
course_num: "M118",
title: "Finite Math"
},
{
course_num: "M119",
title: "Calculus"
}
];
// constructs the suggestion engine
var courseSuggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('course_num'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: courses
});
var methods = {
init : function(options) {
},
add : function( ) {
// Adds a new row to my table
}
};
$.fn.studentCourseBox = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.studentCourseBox' );
}
};
})( jQuery );
The idea is that each time I add a new row using this plugin:
$('#myWidget').studentCourseBox('add')
,
it will automatically initialize a Typeahead field in one of the columns. Unfortunately, I get a Javascript error "ReferenceError: Bloodhound is not defined" at the first reference to Bloodhound.
However if I move the variable initializations for courses
and courseSuggestions
outside of the plugin, and pass them in via the init
method, it works just fine. So, I know that Bloodhound works in my script, it just doesn't work inside my plugin.
What am I doing wrong? I feel like this is a scoping issue, but I've tried $.Bloodhound
, $.fn.Bloodhound
, etc and nothing works.