Required code cannot access main code - javascript

so I was trying to bring my code to readable form but stumbled upon a kinda annoying problem.
So I wanted to outsource a class into an file, "require" it and than write the callback function in the main file for the readability. But the function in the outsourced file is not able to access the callback function. Here is the simplified problem:
file_a.js
function test_a(){
return "this is A"
}
var test_b = require('./lib/file_b.js').test_b
console.log(test_b())
file_b.js
function test_b(){
return test_a()
}
exports.test_b = test_b
I hope someone could tell me how to manage this problem :)
EDIT: This code is for a firefox addon !

test_a function has to be globally defined:
test_a = function(){
return "this is A"
}
var test_b = require('./lib/file_b.js').test_b
console.log(test_b())
Also, you have to return something in your test_b function:
function test_b(){
return test_a()
}
exports.test_b = test_b
Then you will have such output:
this is A

You can load both js files independently in the same HTML file.
Then, whichever code that you have that is referencing other files loaded on the page should be in a window.onload call (or using jQuery $(document).ready), so that it only runs when the two files are available on the page.

Related

Javascript: usage of require in Appcelerator Titanium

I am quite new to javascript and I am struggling with a simple problem. I have to split up codes into separate files. As an example I have a file called Database.js. In that file I have the following lines:
function Database(){
//someStuff
this.fetchAll = function(){
//some stuff
return something;
}
}
Now I want to use the Database.js code in the file app.js. So I write the following code in app.js:
var Database = require('Database');
var myDB = new Database();
var result = myDB.fetchAll();
However, I get the error Script Error = '[object Database]' is not a constructor (evaluating 'new Database()') at app.js (line 3).
What is my mistake?
Before you moving to the development, you need to understand thoroughly about CommonJS Modules in Titanium. Then it will be more simple for you. Also refer the require function
Let's come to your error. [ERROR] [object Database]' is not a constructor (evaluating 'new Database()') at app.js (line 3) means that the module you created is not constructor. Your constructor function might not return any value. Read simple usage of CommonJS module. I'm sure it will resolve your issue.
There is an alternative way, you can include your Database.js file in your app.js. You does not need to return anything and no need to use require function. You just need to use the include method. Just write Ti.include('Database.js'); inside your app.js and you can access all the global variables and functions inside the Database.js file
This question is old but it has not been answered yet. So i will just provide the answer for anyone who is visiting here.
You have to export you function as global. To do so you would declare it as below
exports.fetchAll = function Database(){
//some stuff
return something;
};
You can also declare the function so that it can be used globally as well as locally within the file
var fetchAll = function Database(){
//some stuff
return something;
};
exports.fetchAll = fetchAll;
Then assuming the file name is Database and it is in same folder as app.js, you can use it as below
var Database = require('Database');
var result = Database.fetchAll();
edit: This answer is javascript general and it's not oriented towards Appacelerator Titanium.
There is no such include or require in javascript. You can on the other hand do one of the following
Include a script tag before your script to include Database.js
<script type="text/javascript" src="Database.js" >
OR
Add it dynamically
function loadScript(url, callback)
{
// adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// then bind the event to the callback function
// there are several events for cross browser compatibility
script.onreadystatechange = callback;
script.onload = callback;
// fire the loading
head.appendChild(script);
}
The problem seemed to be the usage of the variable name 'Database'. Maybe there is somewhere a name collusion.
I am sorry that I did not know that the usage of require is not a basic concept of js.
Just a quick guess here. If you use CommonJS then you have to tell what should be available outside of the module. The way you lay out that you have made the Database "object" you would need to add:
module.exports = Database;
somewhere in your module. I always put them at the end - but not sure that is a requirement.
You can also make individual functions available outside of a module by specifying:
exports.getMyDatabase = getMyDatabase;
Where "getMyDatabase" is a function you have specified in the module. I use this way to "hide" certain implementation details of some functions from the outside and just make available the functions I want the developer to be able to call ;-)
/John
I think this is the right usage of require js:
require(["Database"], function() {
var myDB = new Database();
var result = myDB.fetchAll();
});
http://requirejs.org/docs/jquery.html

Dynamic JavaScript files on Ajax Request creating conflict

I am using MVC3 with heavy usage of ajax to get Partial Views. If Partial view contains JavaScript then it is added as a new js file as shown in snapshot:
so If I have a js function:
function checkValue(){
//do work
}
on ajax call a new dynamic JS file will be added contained this function and it conflicts with old once.
myfile.js contained:
function checkValue(){
//do work
}
and 1.js (dynamic file) will contain it too
function checkValue(){
//do work
}
So when I call it due to presence in old file it call already present function which is outdated. How to solve this situation like new JavaScript replace old one.
Thanks
You can check whether something is defined and redefine it only if it is not:
var checkValue = checkValue || function () {
//do work
};
If you want your definitions to override each-other instead of defining the function with a name, define them on the global object each time:
window.checkValue = function () {
//do work
};

Detect when a method is being run in javascript (event)

Im looking to inject a variable into a page before a method is run. The situation is as follow
CUSTOM JS CAN GO HERE
my.var = 'cake';
my.function();
I dont have access to be able to modify the page directly, however there is a content area at the top of the page I can add some JS if i need to. Basically i need to overwrite the my.var variable with something else before my.function() is run. Is there a way to do this? (the site is running jQuery 1.4.2.
Thanks
Dan
Basically i need to overwrite the my.var variable with something else before my.function() is run. Is there a way to do this?
var oldfunction = my.function;
my.function = function () {
my.var = "whatever you want";
oldfunction.apply(this, arguments);
}
This is, of course, if my or my.function isn't overwritten by the code you can't modify directly before the call to my.function (as my.var is).
For example, in the following scenario:
///your code goes here
///code you cannot modify below
var my = {};
my.function = something;
my.var = 'cake';
my.function();
what you want is impossible (unless you're able to redefine something or something in it in the same way).
Basically, in this case the only thing you could do is to write (let's assume something is function () { alert(my.var) })
var oldalert = window.alert;
window.alert = function (message) {
oldalert(message === 'cake' ? 'whatever you want' : message);
}
Well, you've got an idea.
Injecting some code in between my.var = 'cake'; and my.function(); is, from the other side, imposible. Roughly speaking, you can choose between two options, whether your code will be executed before my.var = 'cake'; or after my.function();. Executing your code aftre my.var = 'cake'; but before my.function(); is impossible (if we're speaking of a production environment; of course you could do anything by hands using the debugger, if you need to modify my.var for a debugging purpose).

Jquery and javascript namepsace

In trying to namespace my js/jquery code, I have come up against the following problem.
Basically, I used to write all my JS code in each html/php file, and I want to abstract that away to a single js file with namespaces.
So, in my html file I have:
<script type="text/javascript">
$(document).ready(productActions.init());
</script>
And in my js file I have:
var productActions = {
init: function() {
alert('initialsed');
$('#field_id').change(function() {
alert('ok!');
});
}
The productActions init function is definitely running, because I get the first alert (initialised). However, it seems that none of the jquery binding functions do anything at all. Stepping through the init function shows that the above change function is being registered, but actually changing the value in the field does absolutely nothing.
Am I missing something obvious here?
$(document).ready(productActions.init());
This code calls init() immediately and passes its return value to ready(...). (just like any other function call)
Instead, you can write
$(document).ready(productActions.init);
To pass the function itself. Howeverm this will call it with the wrong this; if you need this, write
$(document).ready(function() { productActions.init() });

Unable to re-define a function in my javascript object

I have an object defined using literal notation as follows (example code used). This is in an external script file.
if (RF == null) var RF = {};
RF.Example= {
onDoSomething: function () { alert('Original Definition');} ,
method1 : function(){ RF.Example.onDoSomething(); }
}
In my .aspx page I have the following ..
$(document).ready(function () {
RF.Example.onDoSomething = function(){ alert('New Definition'); };
RF.Example.method1();
});
When the page loads the document.ready is called but the alert('Original Definition'); is only ever shown. Can someone point me in the right direction. I basically want to redefine the onDoSomething function. Thanks, Ben.
Edit
Thanks for the comments, I can see that is working. Would it matter that method1 is actually calling another method that takes the onDoSomething() function as a callback parameter? e.g.
method1 : function(){
RF.Example2.callbackFunction(function() {RF.Example.onDoSomething();});
}
Your code as quoted should work (and does: http://jsbin.com/uguva4), so something other than what's in your question is causing this behavior. For instance, if you're using any kind of JavaScript compiler (like Closure) or minifier or something, the names may be being changed, which case you're adding a new onDoSomething when the old one has been renamed. Alternately, perhaps the alert is being triggered by something else, not what you think is triggering it. Or something else may have grabbed a reference to the old onDoSomething (elsewhere in the external script, perhaps) and be using it directly, like this: http://jsbin.com/uguva4/2.
Thanks for the response .. in the end the answer was unrelated to the code posted. Cheers for verifying I wasn't going bonkers.

Categories