I want to add a getter and a setter for the $
object, similar to the val()
function for a DOM object.
If the val
is called without parameters, the getter is invoked. With one parameter, the setter is invoked.
I have tried with
$.fn.simpleSearch = function() {
return _variable;
}
$.fn.simpleSearch = function (search) {
_variable = search;
}
But it does not work.
Any hint?
CodePudding user response:
You cannot define $.fn.simpleSearch
twice. The 2nd definition will override the first.
You can set up a simple getter and setter like this:
$.fn.simpleSearch = function (search) {
if ( typeof search != 'undefined' ) {
_variable = search;
}
return _variable;
}
console.log( $(jQuery).simpleSearch() )
console.log( $(jQuery).simpleSearch('foo') )
However, this code is not complete because _variable
needs to be defined somewhere. Do you intend it to be a global variable? A property of an object?
Also see How to create custom JQuery function and how to use it?