-1

I keep getting the error 'validate is not a function'

function someObj( nameOfObj ) {
    this.nameOfObj = nameOfObj;
    var create = '<input id=' + nameOfObj + '>';
    document.write(create);


    someObject.prototype.validate = function(  ) {
        //nonsense
    }

    jQuery( '#' + this.nameOfObj ).bind( 'input', function(  ) {

        this.validate(  ); //or validate(  ); <------- Not working here

    } );    

}

I want to create an object that is a self validating <input> as the user types, it will execute valitdate( ) and I want to bind this validation during instantiation.

Patrick Pease
  • 179
  • 1
  • 8

2 Answers2

0

Is the use of the prototype really needed? It just seems to work in this way:

function someObj( nameOfObj ) {
    this.nameOfObj = nameOfObj; //changed here
    var create = '<input id=' + nameOfObj + '></input>';
    document.write(create);


    this.validate = function(  ) { //changed here
        //nonsense
    }

    jQuery( '#' + this.nameOfObj ).bind( 'input', function(  ) {

        this.validate(  ); //or validate(  ); 

    } );    

}
D. Melo
  • 2,139
  • 2
  • 14
  • 19
  • The `this` value of `this.validate` is an Element object not a someObj object. – HMR Nov 20 '13 at 01:39
  • but when I print that "this" to the console, I have an instance of someObj // CODE // this.validate = function( ) { //changed here //nonsense }; console.log(this); – D. Melo Nov 20 '13 at 04:16
  • If you run the following on this page (in the console) and click on a code block then it'll log the element: `jQuery( 'code' ).bind( 'click', function( ) { console.log("and this is:",this); }); ` – HMR Nov 20 '13 at 04:39
0

Are you using an old version of JQuery? Since version 1.7 the on method is preferred to bind.

You don't have provide the validate function in the constructor function, my guess is that you can't get it to work because this in the bound function refers to the Element. Here is how you should do it:

function someObj( nameOfObj ) {
    this nameOfObj = nameOfObj;
    //there are better ways of doing this: 
    // http://api.jquery.com/?s=append
    var create = '<input id=' + nameOfObj + '></input>';
    document.write(create);
    var me = this;
    jQuery( '#' + this.nameOfObj ).bind( 'input', function(  ) {
        me.validate(  ); //or validate(  ); <------- Not working here

    } );
}
someObject.prototype.validate = function(  ) {
    console.log("and this is now:",this);
    //nonsense
}

Introduction to constructor functions, prototype and the value of this here.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160
  • I didn't know about JS scope binding until your response. Here is an article that describes it fairly well for anybody having the same problem. http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/ – Patrick Pease Nov 28 '13 at 16:28