2015-11-06 56 views
-1

我定義爲這樣一個基本的jQuery插件裏面:使用事先鍵入的內容警犬一個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未定義」。

但是,如果我將插件外部的coursescourseSuggestions的變量初始化移動並通過init方法傳遞它們,它就可以正常工作。所以,我知道Bloodhound在我的腳本中起作用,它在我的插件內不起作用

我在做什麼錯?我覺得這是一個範圍問題,但我試過$.Bloodhound$.fn.Bloodhound等,沒有任何工作。

回答

0

我把我的Javascript包括在錯誤的順序。我的Bloodhound的JS資源在之後加載了這個代碼,所以我的瀏覽器必須在Bloodhound被定義之前嘗試實例化courseSuggestions。但是,不知道爲什麼它在插件外部實例化時工作。