Using jQuery as suggested by Wordpress, I have wrapped my code in an anonymous function so that jQuery will not conflict with other javascript libraries:
(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
})(jQuery);
The problem is that I want to split my code into two files: 1) main.js and 2) utility.js.
How can the main program (main.js) call functions within the other file (utility.js) when both are encapsulated?
utility.js
(function($) {
function doSomething() {
/* code here */
}
})(jQuery);
main.js
(function($) {
$(document).ready(function(){
doSomething();
}
})(jQuery);
Thanks
You can use to return an object out of this utility.js:
(function($, win) {
win.util = function(){
this.doSomething = function() {
$('pre').append('util.js');
}
};
})(jQuery, window);
(function($, $U) { // <----referred it with $U
$(document).ready(function() {
$U.doSomething();
});
})(jQuery, new util()); //<----pass the util object here.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Actually i like the way to use it in OOJS way. Try creating a constructor and pass a new object.
The simplest solution is to assign all functions in utility.js to some global object. Assuming your code works in the browser you could do something like this:
utility.js
(function($, context) {
context.Utility = {
doSomething: function() {
/* code here */
}
};
})(jQuery, window);
main.js
(function($, Utility) {
$(document).ready(function(){
Utility.doSomething();
}
})(jQuery, Utility);
A more general solution would be to use asynchronous module loading (http://requirejs.org/) or a tool like JSPM to manage modules in your application.
Related
I have a panel widget with a button. Clicking the button should execute some global actions related to all such widgets and after that execute some local actions related to this widget instance only. Global actions are binded in a separate javascript file by CSS class like this:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
jQuery(document).ready(function()
{
App.init();
});
And in the html file local script is like this:
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
Currently local script is executed first and global only after while I want it to be the opposite. I tried to wrap local one also with document.ready and have it run after global but that doesn't seem to change the execution order. Is there any decent way to arrange global and local jQuery bindings to the same element?
The problem you're having comes from using jQuery's .ready() function to initialize App, while you seem to have no such wrapper in your local code. Try the following instead:
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
$(function()
{
App.init();
});
Then in your local JS:
$(function() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
});
Note that $(function(){}) can be used as shorthand for $(document).ready(function(){});. Also, make sure your JS file is located before your local JS, as javascript runs sequentially.
Alternatively, you can use setTimeout() to ensure everything's loaded properly:
(function executeOnReady() {
setTimeout(function() {
// Set App.isInitialized = true in your App.init() function
if (App.isInitialized) runLocalJs();
// App.init() hasn't been called yet, so re-run this function
else executeOnReady();
}, 500);
})();
function runLocalJs() {
$("#widgetBtn1234").click(function (e)
{
// do smth local
});
};
How about this instead:
var widget = $("#widgetBtn1234").get(0);//get the vanilla dom element
var globalHandler = widget.onclick; //save old click handler
// clobber the old handler with a new handler, that calls the old handler when it's done
widget.onclick = function(e){
//do smth global by calling stored handler
globalHandler(e);
//afterward do smth local
};
There might be a more jqueryish way to write this, but I hope the concept works for you.
-------VVVV----keeping old answer for posterity----VVVV--------
Why not something like this?
var App = function ()
{
var handleWidgetButton = function ()
{
$('.widgetBtn').on('click', function (e)
{
// do smth global
if(this.id === 'widgetBtn1234'){
//do specific things for this one
}
});
return {
init: function ()
{
handleWidgetButton();
}
};
}
}();
Please excuse any syntax errors I might have made as I haven't actually tested this code.
Check out my simple JQ extension I created on jsbin.
http://jsbin.com/telofesevo/edit?js,console,output
It allows to call consequentially all defined personal click handlers after a global one, handle missed handlers case if necessary and easily reset all personal handlers.
I have a question about javascript module pattern with JQuery.
Im a little confused about how i should use jquery. I have all my javascript modules in seperate files.
Lets say I have a small module
var jqueryTest = (function () {
function privateMethod() {
$("input[type=submit], a, button")
.button()
.click(function () {
alert("ALARM");
});
}
return {
test: function () {
privateMethod();
}
};
})();
I then call the module from my index and it works.
I then tried to pass JQuery as a parameter like this
var jqueryTest = (function (jq) {
function privateMethod() {
jq("input[type=submit], a, button")
.button()
.click(function () {
alert("ALARM");
});
}
return {
test: function () {
privateMethod();
}
};
})(JQuery);
But then it stops working?
The word "JQuery" thats passed as a parameter, what does this refer to?
And how should I use JQuery when having the javascript in different files?
Hope someone can help
you have a typo. its jQuery. not JQuery
Try using jQuery instead of JQuery:
Example:
html:
<div id="myDiv"></div>
javascript:
var jqueryTest = (function (jq) {
jq("#myDiv").html('<label>Hi there!</label>');
return "hi " + jq("#myDiv").text();
})(jQuery);
alert(jqueryTest);
I've been experimenting with writing JQuery plugins lately, and I'm sure this is a very simple question. But, I seem to not be able to get a value inside of my plugin.
For example, I have the following code:
plugin.js
$(function($) {
$.fn.myPlugin = function() {
// alert the id from main.js
}
});
main.js
$(document).ready(function() {
$('#someDIV').attr('id').myPlugin();
});
You cannot define plugin on string. Use selector to call the plugin.
Have a look at this.
Use it like this:
(function ($) {
$.fn.myPlugin = function () {
this.each(function () {
// Allow multiple element selectors
alert(this.attr('id'));
});
return this; // Allow Chaining
}
} (jQuery));
$('.myClass').myPlugin();
DEMO
Tutorial
Try this:
(function($) {
$.fn.myPlugin = function() {
alert($(this).attr('id'));
}
}(jQuery));
See here: http://jsfiddle.net/1cgub37y/1/
You should pass only the object into your jQuery-extension function (not the object's ID), as below or in this fiddle (will alert "someDIV" onload):
// jQuery extension
// The object passed into jQuery extension will occupy keyword "this"
$(function($) {
$.fn.myPlugin = function() {
// Get the ID (or some other attr) of the object.
var id = $(this).attr("id");
// Now do something with it :)
alert(id);
}
});
$(document).ready(function() {
$('#someDIV').myPlugin();
});
I'm having a very strange and frustrating problem with RequireJS. When I call require for a module with a list of dependencies, all dependencies available in the callback reference a single module. This is probably easier to explained with code:
Including require.js script (with no data-main attribute)
<script type="text/javascript" src="/js/common/require.min.js" ></script>
Below that I include require my main.js (used in all pages of the site) which in the callback requires my page specific js.
<script type="text/javascript">
require(['/js/require/main.js'], function () {
require(['page/home_page']);
});
</script>
main.js
requirejs.config({
baseUrl: 'js/require'
});
requirejs(['base'],
function() {
var base = require('base');
base.init();
});
home_page.js
define(['home','searchbar'], function (home,searchbar){
console.log(home.init == searchbar.init); // This is always true !!!
home.init();
searchbar.init();
});
home.js
define(function(){
this.init = function(){
console.log('in home page');
}
return this;
});
searchbar.js
define(function(){
this.init = function(){
console.log('Now in the searchbar init')
}
return this;
});
The issue is in home_page.js both modules home and searchbar reference the same thing. What's strange is that now that I've simplified this example, it seems pretty random which one it chooses. Most times it's searchbar but every few refreshes it will be home.
Anyone have an ideas? Is it something terribly obvious?
EDIT: Simplified example and provided all module source.
You are assigning to this in both modules. This is not a good idea (excuse the pun). this will possibly be the window object in both cases. You could check by adding a
window.init === searchbar.init
test.
Rewrite the modules to return unique objects, like so:
define(function() {
return {
init: function() {
console.log('in home page');
}
};
});
and
define(function() {
return {
init: function() {
console.log('Now in the searchbar init');
}
};
});
How do you call function lol() from outside the $(document).ready() for example:
$(document).ready(function(){
function lol(){
alert('lol');
}
});
Tried:
$(document).ready(function(){
lol();
});
And simply:
lol();
It must be called within an outside javascript like:
function dostuff(url){
lol(); // call the function lol() thats inside the $(document).ready()
}
Define the function on the window object to make it global from within another function scope:
$(document).ready(function(){
window.lol = function(){
alert('lol');
}
});
Outside of the block that function is defined in, it is out of scope and you won't be able to call it.
There is however no need to define the function there. Why not simply:
function lol() {
alert("lol");
}
$(function() {
lol(); //works
});
function dostuff(url) {
lol(); // also works
}
You could define the function globally like this:
$(function() {
lol = function() {
alert("lol");
};
});
$(function() {
lol();
});
That works but not recommended. If you're going to define something in the global namespace you should use the first method.
You don't need and of that - If a function is defined outside of Document.Ready - but you want to call in it Document.Ready - this is how you do it - these answer led me in the wrong direction, don't type function again, just the name of the function.
$(document).ready(function () {
fnGetContent();
});
Where fnGetContent is here:
function fnGetContent(keyword) {
var NewKeyword = keyword.tag;
var type = keyword.type;
$.ajax({ .......
Short version: you can't, it's out of scope. Define your method like this so it's available:
function lol(){
alert('lol');
}
$(function(){
lol();
});
What about the case where Prototype is installed with jQuery and we have noconflicts set for jQuery?
jQuery(document).ready(function($){
window.lol = function(){
$.('#funnyThat').html("LOL");
}
});
Now we can call lol from anywhere but did we introduce a conflict with Prototype?