该插件具有此变量
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
问题是,当我定义一个新实例时,我想向this.onValid添加一个新函数,我不想覆盖默认事件?
如何扩展变量this.onValid?
答案 0 :(得分:3)
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
//That above is already defined;
this._onValid = this.onValid; //Make a backup function
this.onValid = function (){
this._onValid(); //Call the actual function
//Your extended code here //Call your code
}
这是特定于您的代码。为了更好地理解它,也许这个例子会有所帮助:
writeA = function (){
document.write('a');
};
//Now I want to extend the writeA function to write 'b' as well
_writeA = writeA;
writeA = function (){
_writeA(); //So now I call whatever the function originally did
document.write('b'); //And now I execute what I want to add to the function
};
刚刚尝试修复您在评论中提供的代码。试试这个:
var obj1 = {
this._onValid = this.onValid; //Do this assuming this.onValid is already defined
onValid: function(){ //Redefine it
this._onValid();
newFunction();
}
};
来自插件。只需将其编辑为如下所示:
this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };
this._onValid = this.onValid;
this.onValid = function (){
this._onValid();
//YOUR CODE HERE
};
我已将原始文件编辑为here.
哈,刚刚意识到我在这里开始使用与我在开头时相同的代码。好吧,那是因为它的完全应该是什么样子。查看我编辑过的文件并搜索//YOUR CODE HERE
并在那里添加您的代码。