【发布时间】:2015-11-06 14:40:13
【问题描述】:
我有一个这样定义的基本 jQuery 插件:
(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 );
这个想法是每次我使用这个插件添加一个新行:
$('#myWidget').studentCourseBox('add'),
它将自动在其中一列中初始化一个 Typeahead 字段。不幸的是,我在第一次引用 Bloodhound 时收到 Javascript 错误“ReferenceError: Bloodhound is not defined”。
但是,如果我将 courses 和 courseSuggestions 的变量初始化移到插件之外,并通过 init 方法传递它们,它就可以正常工作。所以,我知道 Bloodhound 在我的脚本中有效,只是在在我的插件中无效。
我做错了什么?我觉得这是一个范围界定问题,但我尝试了$.Bloodhound、$.fn.Bloodhound 等,但没有任何效果。
【问题讨论】:
标签: jquery jquery-plugins scope typeahead.js bloodhound