0

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.

4

1 回答 1

1

好的,两个问题

templates.js,一旦你定义了一个对象或函数,你必须返回它

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

在 中main.js,您必须为这些定义的对象提供参考名称,除非它们不是 AMD 或在 shim 配置中定义。

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

试一下!

于 2013-07-16T04:49:39.293 回答