2016-05-17 60 views
0

我想創建我的第一個插件,當我加入一個項目叫add功能,所以對象記錄,但獲得有關onAdd is undefined錯誤(見下文)插件方法未定義

這裏是插件

$(function() { 
    var settings = { 
     onAdd: function() {}, 
     onRemove: function() {}, 
     sourceSelecter: null, 
     targetSelector: null 
    }; 

    $.fn.tokenizer = function (options) { 

     settings = $.extend({ 
      targetSelector: this, 
      idName: 'id' 
     }, options); 

     this.add = function (item) { 
      console.log (settings) 
      settings.onAdd.call(item); 
     }; 

     this.remove = function (item) { 
      settings.onRemove.call(item); 
     }; 
     return this; 
    }; 
}(jQuery)); 

這裏是控制檯:

Object { targetSelector: Object, idName: "id", sourceSelector: "group" }

TypeError: settings.onAdd is undefined

有人可以enlighened我,爲什麼會出現在我的沒有onAdd功能?

回答

0

您在擴展時不包含原始settings對象。另外我建議你創建this.settings字段,以保持默認settings分開:

$(function() { 
    var settings = { 
    onAdd: function() {}, 
    onRemove: function() {}, 
    sourceSelecter: null, 
    targetSelector: null 
    }; 

    $.fn.tokenizer = function(options) { 
    this.settings = $.extend({}, { 
     targetSelector: this, 
     idName: 'id' 
    }, settings, options); 

    this.add = function(item) { 
     console.log(this.settings) 
     this.settings.onAdd.call(item); 
    }; 

    this.remove = function(item) { 
     this.settings.onRemove.call(item); 
    }; 
    return this; 
    }; 
}(jQuery));