Inheritance with wp_enqueue_scripts() - javascript

I'm trying to build a plugin in wordpress, and I've encountered this issue where I need to include a .js from another plugin into my own. I tried it using wp_enqueue_script() by adding the other .js as a dependency for my .js, but to no avail.
wp_enqueue_script('parent-script', '/parent-script.js', array('jquery'), false);
wp_enqueue_script('child-script', '/child-script.js', array('jquery', 'parent-script'), false);
I need to call a variable from the parent-script and use it in the child-script. Is it possible? If so, how do I proceed with it?
Edit : Removed the parent-script dependency from the parent-script enqueue, following the comment of Chris.
Also, to be more specific, suppose parent-script is this :
jQuery(function($){
var foo = "This is from parent script";
});
Will using wp_enqueue_script() like I have above let me use foo from the child script? If not, is there any way for me to access it from the child script?

Related

How to put external js API in cocos creator?

I am just wondering how to put another js API library( in my case, i want to put the smartfoxserver javascript API library) in cocos creator? because what i did in cocos2d-js, i just need to add it in project.json, and I am wondering if i can do same way in cocos creator or another way?
thank you in advance
reference question from:
http://discuss.cocos2d-x.org/t/how-to-put-another-js-api-library-in-cocos-creator/32598
good day
you can use module exports
var x = {
/*
your stuff
*/
};
module.exports = x;
then access it from other scripts using
var externalScript=require("name of the script with module.exports");
cheers
i just scan the smartfoxserver. it use the websocket that is fine just drag an drop the SFS2X_API_JS.js to the project and require it and init it maybe you would use window.xxx to set the connection handler as global value

Give preference to JS file function over HTML file

I have two functions of the same name; let's say foo().
One in the HTML file and one in the JS file, which is included in the HTML file. The problem is I want to give preference to the JS file function rather than the HTML file function.
Is there any way to do that, or is there any syntax in JavaScript like [JSFileName].foo(), that may perhaps call the function in the JS file?
Not sure why you want to have two identically-named functions.
The snarky answer is: Just remove the reference to the function you don't want. (If you have control over your html, such a situation shouldn't exist.)
The answer you're looking for: Place the external script tag after the inline script tag.
Make sure the script tag for the js file is after the HTML script tag in which foo is declared.
It's not clear from your question why you have two functions named foo, but based on your [JSFileName].foo() attempt at a solution, I might suggest using objects as namespaces. In your script you could do:
var myScriptFunctions = {
foo: function() {
// do foo stuff
}
}
You can call it with myScriptFunctions.foo() and you won't have two functions competing for the global name foo.

Is There Any Way To Include a Javascript File Inside Another JS File?

I have tried 3 suggestions found in other questions on the site but none seem to work for me and I'm not sure why.
// #1
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.getElementsByTagName('head')[0].appendChild(imported);
// #2
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
// #3
document.write( '<script language="javascript" src="myotherscript.js" />' );
The file I am trying to include is basically a massive file with variables declared like so:
var agent = [
"csv",
"drawfile",
"excel",
"flash",
"hangul",
"html",
"image",
"msword",
"ooxml",
"pdf",
"ppt",
"txt",
"wmf"];
Any ideas on what could be causing the problem?
UPDATE
Just an update to say that the JS file that I'm trying to include is generated dynamically from a database, so avoid regular expressions to add and remove the same bit of code constantly I have it stored in a serparate file.
The variables concerend are used to populate a dynamic drop down list with the values, so by not working I mean no values in the dropdowns :(
I would use require plugin for now I think jquery will have this in the next core release 1.6
If the sole purpose is to include another javascript file to declare a bunch of variables and their values into the global scope, why not just <script type="text/javascript" src="myotherscript.js"></script> in the head of your html document before your other script source includes?
Edit:
The problem is that you cannot define global variables from within a method. You do have the plausible option of encapsulating your whole script file (or at least the affected portions) in a jQuery ajax function which evaluates your included file first thing. That would leave your included variables in the correct scope. Here is what I mean...
$.ajax({
url: 'path/to/included/file',
success: function(msg) {
eval(msg); // This is where your included variables are in regard to scope
// This is where you would paste all of your dependent functions and whatnot
}
});
// Outside of the ajax method, you won't be able to use your included properties
var getScript = function(jsPath) {
$.ajax({
dataType:'script',
async:false,
cache:true,
url:jsPath
});
};
http://requirejs.org/ is the most popular for this kind of problem
Thank you everyone for your help but I think the cause of the errors was some characters that needed escaping within the variables.
Martin

How to isolate different javascript libraries on the same page?

Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself.
Suppose third party page also uses jquery but a different version.
How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it.
Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example.
What solutions are exist to isolate different javascript libraries aside from obvious iframe?
Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
Actually, I think jQuery.noConflict is precisely what you want to use. If I understand its implementation correctly, your code should look like this:
(function () {
var my$;
// your copy of the minified jQuery source
my$ = jQuery.noConflict(true);
// your widget code, which should use my$ instead of $
}());
The call to noConflict will restore the global jQuery and $ objects to their former values.
Function(...) makes an eval inside your function, it isn't any better.
Why not use the iframe they provide a default sandboxing for third party content.
And for friendly ones you can share text data, between them and your page, using parent.postMessage for modern browser or the window.name hack for the olders.
I built a library to solve this very problem. I am not sure if it will help you of course, because the code still has to be aware of the problem and use the library in the first place, so it will help only if you are able to change your code to use the library.
The library in question is called Packages JS and can be downloaded and used for free as it is Open Source under a Creative Commons license.
It basically works by packaging code inside functions. From those functions you export those objects you want to expose to other packages. In the consumer packages you import these objects into your local namespace. It doesn't matter if someone else or indeed even you yourself use the same name multiple times because you can resolve the ambiguity.
Here is an example:
(file example/greeting.js)
Package("example.greeting", function() {
// Create a function hello...
function hello() {
return "Hello world!";
};
// ...then export it for use by other packages
Export(hello);
// You need to supply a name for anonymous functions...
Export("goodbye", function() {
return "Goodbye cruel world!";
});
});
(file example/ambiguity.js)
Package("example.ambiguity", function() {
// functions hello and goodbye are also in example.greeting, making it ambiguous which
// one is intended when using the unqualified name.
function hello() {
return "Hello ambiguity!";
};
function goodbye() {
return "Goodbye ambiguity!";
};
// export for use by other packages
Export(hello);
Export(goodbye);
});
(file example/ambiguitytest.js)
Package("example.ambiguitytest", ["example.ambiguity", "example.greeting"], function(hello, log) {
// Which hello did we get? The one from example.ambiguity or from example.greeting?
log().info(hello());
// We will get the first one found, so the one from example.ambiguity in this case.
// Use fully qualified names to resolve any ambiguities.
var goodbye1 = Import("example.greeting.goodbye");
var goodbye2 = Import("example.ambiguity.goodbye");
log().info(goodbye1());
log().info(goodbye2());
});
example/ambiguitytest.js uses two libraries that both export a function goodbye, but it can explicitly import the correct ones and assign them to local aliases to disambiguate between them.
To use jQuery in this way would mean 'packaging' jQuery by wrapping it's code in a call to Package and Exporting the objects that it now exposes to the global scope. It means changing the library a bit which may not be what you want but alas there is no way around that that I can see without resorting to iframes.
I am planning on including 'packaged' versions of popular libraries along in the download and jQuery is definitely on the list, but at the moment I only have a packaged version of Sizzle, jQuery's selector engine.
Instead of looking for methods like no conflict, you can very well call full URL of the Google API on jQuery so that it can work in the application.
<script src="myjquery.min.js"></script>
<script>window.myjQuery = window.jQuery.noConflict();</script>
...
<script src='...'></script> //another widget using an old versioned jquery
<script>
(function($){
//...
//now you can access your own jquery here, without conflict
})(window.myjQuery);
delete window.myjQuery;
</script>
Most important points:
call jQuery.noConflict() method IMMEDIATELY AFTER your own jquery and related plugins tags
store the result jquery to a global variable, with a name that has little chance to conflict or confuse
load your widget using the old versioned jquery;
followed up is your logic codes. using a closure to obtain a private $ for convience. The private $ will not conflict with other jquerys.
You'd better not forget to delete the global temp var.

Javascript "<body onload=...>" in Drupal

I'm trying to integrate a javascript library for drag&drop on tables into one page of my custom Drupal module. I've included the js file using drupal_add_js, but I don't know how to initialize it.
The documentation for that library states that an init function should be called like
<body onload="REDIPS.drag.init()">
How would I do that in Drupal? Or has Drupal some better way of initializing the script?
Drupal has its own mechanism for this, involving adding a property to Drupal.behaviors. See this page: http://drupal.org/node/205296
Drupal.behaviors.redipsDragBehavior = function() {
REDIPS.drag.init();
};
From the linked page:
Any function defined as a property of
Drupal.behaviors will get called when
the DOM has loaded.
You could try adding another drupal_add_js call in the same function as your other add_js:
drupal_add_js('REDIPS.drag.init();','inline','header',true);
The last param "true" is to defer the execution of the script.
I hope that helps in some way!

Categories

Resources