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);
Related
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 trying to create a simple plugin that I can call by both: $.myPlugin() and $('something').myPlugin()
Heres the code:
(function($) {
$.fn.myPlugin = function(item) {
return this;
};
$.myPlugin = function(item) {
return $.fn.myPlugin(item);
};
}(jQuery));
This works when called either way mentioned above.
However, calling $.myPlugin().hide() does not work. Any chained methods are failing.
Heres a simple JSBin I made showing the issue
Why?
You should return $(this), not jquery this:
(function($) {
$.fn.myMethod = function() {
this.append('<p>MY METHOD</p>');
return $(this);
};
$.myMethod = function() {
return $.fn.myMethod();
};
}(jQuery));
$(function () {
// Moment of truth
$('.output').myMethod().hide('slow');
$('h1').click(function(){
$('.output').myMethod().hide();
});
});
Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.
I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/
I'm on a .NET MVC2 project and have a reference to SomeClass.Home.js and jQuery in the masterpage. My SomeClass.Home.js looks like this:
SomeClass.Home = {};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
SomeClass.Home.SomeMethod= function () {
alert("hello");
};
The call to SomeClass.Home.SomeMethod doesn't work (I don't get the alert). However, if I change it to this, it works, and I get the alert:
$(document).ready(function () {
SomeMethod();
});
function SomeMethod () {
alert("hello");
};
Is anything wrong with the syntax of the first one?
The problem seems to be in the way you described the SomeClass variable. The following code works for me.
var SomeClass = {};
SomeClass.Home = {};
SomeClass.Home.SomeMethod = function() {
alert("hello");
};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
Yes, because you're not declaring the method. I believe you should do it like this:
SomeClass.Home = {
SomeMethod = function(){ //stuff });
}
$(function(){ SomeClass.Home.SomeMethod() });
What if you embed the function in the class?
SomeClass.Home = {
SomeMethod= function () {
alert("hello");
};
};
$(document).ready(function () {
SomeClass.Home.SomeMethod();
});
SomeClass.Home.SomeMethod= function () {
alert("hello");
};