0

I am having a lot of issues with jquery. I am managing an older application that used prototype. My new pages don't use prototype, but I am encapsulating things in jquery.noConflict just in case. This however is resulting in me being unable to share functions through different js files.

Order files are loaded:

jquery.js
jquery.commonFuncs.js
jquery.database.js

Example contents of files

commonFuncs.js

var someGlobalVar = "abc";

jQuery.noConflict()(function($){

  function doStuff(x){
     return x;
  }

}); 

database.js

jQuery.noConflict()(function($){
  var a = 123;
  doStuff(a);
});

Error: doStuff is not defined.

I can kind of understand why encapsulating the function removes it from the global namespace. How can I add it back?

I also have no darn idea why I have to use noConflict if I do not load prototype.js If I completely remove prototype.js and remove the noConflict encapsulation, I get $ is undefined, and I don't know where to start with that. jQuery is clearly loading first. No clue.

1
  • 3
    Create a global object and assign the functions you're defining as properties on that object. Commented Dec 17, 2014 at 19:59

2 Answers 2

1

As Madbreaks proposed, something like in the example below should work. (Have a look in the web browser console to see that there's no error message.)

var someGlobalVar = "abc";
var myApp = {};

jQuery.noConflict()(function($){

  function doStuff(x){
     return x;
  }

  myApp.doStuff = doStuff;
}); 

jQuery.noConflict()(function($){
  var a = 123;
  //doStuff(a);
  console.log(myApp.doStuff(a));  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

You can refactor your code like this:

 var someGlobalVar = "abc";
 var doStuff;
 jQuery.noConflict()(function($){

  doStuff = function(x){
     return x;
  }

 }); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.