我在我的网站上使用来自http://code.drewwilson.com/entry/autosuggest-jquery-plugin的 autoSuggest 插件来搜索各种不同的项目。这个插件的一个主要功能是,当添加选择时,会调用一个回调函数,我检查这是添加的新数据还是从 Web 服务获取的数据,然后更新一些变量(我用于提交)
到现在为止,我一直在没有任何想法地使用它,但现在我决定采用 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);
}
我怎样才能做到这一点而不会失去代码的可重用性?