Search code examples
javascriptjqueryjquery-eventsanonymous-types

With a Javascript IFFE getting a Uncaught TypeError is not a function


I was trying to code up some anonymous function IFFE stuff in JavaScript and I don't understand why I am getting this error

Uncaught TypeError: dM.getResources is not a function

Fiddle https://jsfiddle.net/MillerDev/5qmnqr6q/

What is causing it?

reportGroupDataManager ( normally this is reportGroupDataManager.js file)

var reportGroupDataManager = (function() {
   var self = this;
   // cannot do this below   as dM.getResources is not a function
   //self.getResources = "blah";

  self.getResources = function() {
    return object;
     // return ajaxHelper.get(actions.adminReports.getResourceFileUrl, {});
  };

  console.log('reportGroupDataManager');

  return self;
});

data (currently placeholder)

function data() {
   console.log('in data'); 
}

IFFE

(function(jQ, dM, data) {
    var self = this;

    var initializePage = function () {
       console.log('in init');
    };

    dM.getResources()
        .done(initializePage, function(result) {
            console.log('in fx');
            console.log(result);
            console.log(result.CannotDeleteWithChild);
        });

})($, reportGroupDataManager, data);

So normally dM.getResources() is going to fetch data from the reportGroupDataManager in which result is a object

but with this code I'm not sure why the error

same Fiddle as above --> https://jsfiddle.net/MillerDev/5qmnqr6q/


Solution

  • reportGroupDataManager is a constructor, not an object. But you're expecting an object created by reportGroupDataManager. Therefore the IIFE should be this:

    (function(){
       // ...
    })($, new reportGroupDataManager(), data);