将此传递给jQuery插件

时间:2013-04-14 21:12:01

标签: javascript jquery oop jquery-plugins

我在我的网站上使用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);
}

如何在不失去代码的可重用性的情况下执行此操作?

1 个答案:

答案 0 :(得分:0)

我正在回答这个问题,因为我认为我已经通过扩展代码解决了这个问题。我在selectionAdded回调中添加了一个新参数,并在调用时在该函数中提供了函数引用。