Search code examples
javascriptjqueryconstructorpublish-subscribe

Javascript method is not a constructor


at the company where Im at we use jquery and a lot of the code is very spaghetti haphazard code. So in an effort to organize it better im researching implementing the pub sub model described in this article

So I made a really basic version of it like so:

var topics = {};

jQuery.Topic = function( id ) {
    var callbacks, method,
        topic = id && topics[ id ];

    if ( !topic ) {
        callbacks = jQuery.Callbacks();
        topic = {
            publish: callbacks.fire,
            subscribe: callbacks.add,
            unsubscribe: callbacks.remove
        };
        if ( id ) {
            topics[ id ] = topic;
        }
    }
    return topic;
};

$(function() {
    var testService = new TestService();
    testService.subscribe();

    var testView = new TestView(testService);
    testView.initEvents();

});

/* ---------------------VIEW----------------- */
var TestView = function(testService) {
    this.testService = testService;
};

TestView.prototype.initEvents = function () {
    this.publishers();
};


TestView.prototype.publishers = function() {

    $("#search").on("click", function () {
        var isValid = this.testService.validateForm("#container");
        if(isValid){
            $.Topic( "search" ).publish();
        }

    })

};
/* ---------------------SERVICE----------------- */

var TestService = function() {
    this.testIdea = [];

};

TestService.prototype.validateForm = function (section) {
    var referralValid = true;
    $(section).find('input,select').filter('[required]:visible').each(function (i, requiredField) {
        if(requiredField.value === '') {
            //'breaks' the loop out
            referralValid = false;
            return referralValid;
        }
    });
    return referralValid;
};

TestService.prototype.search = function() {


};

TestService.prototype.subscribe = function() {
    var self = this;

    $.Topic("search").subscribe( function() {
        self.search()
    });

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div id="container">
    <input type="text">
  </div>
  <button id="search">Search</button>
</div>

However when I put that in jsfiddle I get the error that Uncaught TypeError: TestService is not a constructor

in the stackoverflow snippet and on my local version I get a different error of Uncaught TypeError: Cannot read property 'validateForm' of undefined. I cant see what Im doing wrong. Any pointers?


Solution

  • You can declare constructor functions in the way you are doing it (assigning constructor to variable):

    var TestView = function(testService) {
        this.testService = testService;
    };
    

    Like in this simple example:

    var myClass = function(name) {
      this.name = name;
    }
    
    myClass.prototype = {
      hello: function() {
        console.log('Hello ' + this.name);
      }
    }
    
    var me = new myClass('Andrew');
    me.hello();

    But you must remember to declare them before they are used. If you use function statement(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) as suggested by Chad Watkins it helps only because of hoisting(http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html) not because of function statement being mandatory for constructors.

    The error in your code is in line:

    $("#search").on("click", function () {
            var isValid = this.testService.validateForm("#container");
    

    you are referencing jQuery object inside a callback not TestView instance, you probably wanted something like this(pun not intended):

    ...
    var self = this;
    $("#search").on("click", function () {
            var isValid = self.testService.validateForm("#container");
    ...