jQuery扩展事件变量

jQuery extend an event variable

本文关键字:变量 事件 扩展 jQuery      更新时间:2023-09-26

插件有这个变量

this.onValid = options.onValid || function(){ this.insertMessage(this.createMessageSpan()); this.addFieldClass(); };

问题是,当我定义一个新的实例,我想添加一个新的函数。onValid,我不想重写默认事件?

如何扩展变量this。onValid吗?

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
  };

我已经编辑了原始文件,看起来像这里。

哈,刚刚意识到我在这里放了和开始时一样的代码。那是因为就是应该有的样子。查看我编辑的文件并搜索//YOUR CODE HERE并在那里添加您的代码。