Reputation: 41
This seems like it should be obvious, but I can not figure out how to properly use namespaced (dotted) function names in jQuery.fn.
More precisely, using this
in a function embedded in an object returns the object.
Not the jQuery object it was attached to via .fn
A simple example that works, not using namespaced functions: (Working example of the below)
$.fn.isBigText=function(nBytes) {
let ttext=this.val();
if (this.val().length > nBytes ) alert('Too big: '+ttext);
}
$.fn.isSmallText=function(nBytes) {
let ttext=this.val();
if (ttext.length < nBytes ) alert('Too small: '+ttext);
}
function checkSize(evt) { // alert if too small or big.
let jqText=$('#myTextArea') ; // should use evt, but for this example I am being explicit
jqText.isBigText(20);
jqText.isSmallText(10);
}
...
<textarea cols="80" rows="1" id="myTextArea" onChange="checkSize(this)">fill this in </textarea>
And a namespaced example that does NOT work. Not defining a .val() function causes a "TypeError: this.val is not a function" error. So for illustrative purposes, I define a .val() within myFuncsDef that always returns "This is not the val() I was looking for!"
// this version does not work
var myFuncsDef={
val: function() {return 'This is not the val() I was looking for! '},
bigText:function(nBytes) {
let ttext=this.val();
if (this.val().length > nBytes ) alert('Too big: '+ttext);
} ,
smallText:function(nBytes) {
let ttext=this.val();
if (ttext.length < nBytes ) alert('Too small: '+ttext);
}
}
$.fn.myFuncs=myFuncsDef ;
function checkSizeNs(evt) { // alert if too small or big (namespaced version)
let jqText=$('#myTextAreaNs') ; // should use evt, but for this example I am being explicit
jqText.myFuncs.bigText(20);
jqText.myFuncs.smallText(10);
}
...
<textarea cols="30" rows="1" id="myTextAreaNs" onChange="checkSizeNs(this)">Fill this </textarea>
Perhaps there is a way of saving the proper value of this (the jqText) before calling an internal function (bigText or smallText)?
Of course I could use something like myFuncs_bigText
instead of myFuncs.bigText
...but that seems like a step backward.
Upvotes: 1
Views: 33