2013-04-14 127 views
1

我在我的網站上使用來自http://code.drewwilson.com/entry/autosuggest-jquery-plugin的autoSuggest插件來搜索各種不同的項目。 這個插件的一個主要功能是,當添加一個選擇時,會調用一個回調函數,並檢查這是新增的數據還是從Web服務中獲取,然後更新一些變量(我用於提交)將此內容傳遞給jQuery插件

直到現在,我一直在使用它沒有任何想法,但現在我決定去OOP的方式,並創建一個JS對象來包裝這個插件和其他相關的功能(常見的回調)和配置值(URL)等。

在這個類中,我有不同的數據變量,這些變量將隨着選擇的添加和刪除而更新。通過代碼的一半,我意識到回調只有一個參數,並且我無法將這些變量或對象的上下文傳遞到這些回調中(對我來說很明顯)

以下是我寫的代碼遠:

var coSuggest = function(options) { 
this.selector = options.selector; 
this.options = options; 
//this.that = this; 
//this.submitURL = options.submitURL; 

//if y=type is not defined , default type will be people 

if (typeof (options.type) === 'undefined') { 
    this.type = 'people'; 
} else { 
    this.type = options.type; 
} 

// if as_options are not defined, as_options will be a empty object 
//console.log(typeof(options.as_options)); 

if (typeof (options.as_options) === 'undefined') { 
    this.as_options = {}; 
} else { 
    this.as_options = options.as_options; 
} 

this.valuesField = $('#as-values-' + this.as_options.asHtmlID); 

//the initData field will be an array of object containing {id,value} of prefilled items initially 
//the addData field will be an array of object containing {id,value} of new selected items from the suggestions 
//the newData field will be an array of strings [values] containing the new values added 
//the removeData field will be an array of objects containing {id,value} of the items from data to be removed 
if (typeof (options.initData) !== 'undefined') { 
    this.initData = options.initData; 
    this.as_options.preFill = this.initData; 

} 
this.as_options.selectionAdded = this.selectionAdded; 

// callback function to be added in as_options as selectionAdded 
this.as_options.selectionRemoved = function(elem) { 
    console.log(elem); 
} 
//return this 

}; 

//urlConf for searching the items sitewide 
coSuggest.prototype.urlConf = { 
people : 'abc', 
interest : "index.php/profile/getInterestsSkillsTags", 
skill : 'xyz', 
teacher : 'xyz', 
designation : 'xyz', 
city : 'xyz', 
subject : 'xyz', 

}; 

// callback function to be added in as_options as selectionAdded 
coSuggest.prototype.selectionAdded = function(elem) { 
//console.log($(this).find('.as-values')); 
console.log(elem); 
} 

//bind function to bind the autoSuggest plugin with the selector provided 

coSuggest.prototype.bind = function(options) { 
//console.log(as_options); 
$(this.selector).autoSuggest(base_url + this.urlConf[this.type], this.as_options); 
} 

我該怎麼做,而不會失去代碼的可用性?

+2

請注意'typeof'是一個操作符而非函數。它有效,因爲你有一個空間。 – elclanrs

+0

哦,我一直無恥地使用typeof這樣沒有意識到。感謝這個事實。然而,這個問題是無關緊要的。 – mlakhara

回答

0

我回答了這個問題,因爲我認爲我通過擴展代碼解決了這個問題。我在selectionAdded回調中添加了一個新參數,並在調用時在該函數中提供了函數引用。