【问题标题】:Using Typeahead Bloodhound inside a jQuery plugin在 jQuery 插件中使用 Typeahead Bloodhound
【发布时间】: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”。

但是,如果我将 coursescourseSuggestions 的变量初始化移到插件之外,并通过 init 方法传递它们,它就可以正常工作。所以,我知道 Bloodhound 在我的脚本中有效,只是在在我的插件中无效。

我做错了什么?我觉得这是一个范围界定问题,但我尝试了$.Bloodhound$.fn.Bloodhound 等,但没有任何效果。

【问题讨论】:

    标签: jquery jquery-plugins scope typeahead.js bloodhound


    【解决方案1】:

    我的 Javascript 包含顺序错误。我有 Bloodhound 的 JS 资源在此代码之后加载,所以我的浏览器必须在定义 Bloodhound 之前尝试实例化 courseSuggestions。不过,不确定为什么在插件外部实例化时它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多