user1330974
user1330974

Reputation: 2616

Cannot initialize an object loaded via requireJS

When I try to initialize an object declared/defined in a different file (but I believe it's been loaded via requireJS), it gives me ReferenceError: myTemplates is not defined. I have two files: main.js and templates.js.

In main.js (which is where I would like to load the object from templates.js and initialize it,

define(["jquery-ui", "templates"], function () {

  var templates = new myTemplates();     // gives ReferenceError
  alert( "Never reached this call" + $().jquery);

  $(document).ready(function() {
    alert( "Never reached this call " + $().jquery);
  });

});

In templates.js, which just have an object named myTemplates with a function named test as follows

define(["jquery-ui"], function () {
  alert( "This alert is raised, proving that jQuery/jQuery UI is loaded in templates.js " + $().jquery);

  function myTemplates(){
    this.test = function(){
      alert('test');
      return false;
    };
  };
});

For the config file for requireJS, named requireconfig.js, I have

requirejs.config({
  "baseUrl": "scripts/lib",
  "paths": {
    "app": "../app",
    "jquery" : [
        "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min", 
        "jquery-1.10.2.min"],
    "jquery-ui" : [
        "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min",
        "jquery-ui-1.10.3.min"],
    "templates" : "../app/templates/templates"
  },

  shim: {
    "jquery-ui": {
       exports: "$",
       deps: ["jquery"]},
  }
});
requirejs(["app/main", "templates"]);

I'm pretty sure the jQuery and jQuery UIs are loaded properly in templates.js, but I can't understand why I'm getting ReferenceError for initializing myTemplates in main.js. Could anyone please take a look and help me out. Thank you.

p.s. The Github upload of the files/folders is here in case anyone wants to look at the folder/file hierarchy.

Upvotes: 0

Views: 362

Answers (1)

Cauliturtle
Cauliturtle

Reputation: 691

OK, two problems

in templates.js, once you defined a object, or function, you have to return it

function myTemplates(){ ... };
return myTemplates;

in main.js, you have to give a reference name for those defined objects, unless they are not AMD or defined in shim config.

define(["jquery-ui", "templates"], function ($ui, myTemplates)

give a try!

Upvotes: 1

Related Questions