Singleton Module & importing global jQuery object
In an attempt to improve the way I code I have been reading about the Singleton Module. Which I think I have fully grasped however I have seen an example that imports jquery as a global, however I was unable to reference a DOM element like below:
var bnTalent = (function ($) {
var bnt = {},
privateVariable = 1;
domRef = $("#pie").val();
function privateMethod() {
// ...
}
bnt.moduleProperty = 1;
bnt.init = function () {
alert("bingo" + domRef);
//domRef.hide();
};
return bnt;
}(jQuery));
HTML:
<!DOCTYPE html>
<html>
<head>
<title>bnTalent</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="js/bnTalent.js"></script>
<link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />
</head>
<body>
<input type="text" id="pie" value="mypies" />
</body>
</html>
Please remember this code is just me playing around to gain an understanding, but wondering why I can not retrieve the value of a DOM element from within the closure. Have I missed the point or have I made some school point error? Please note the element exists in the DOM and jQuery is loaded before this module. Also this is not an attempt at creating a jQuery plugin.
Any help would be greatly appreciated.
Please note I am just using firebug to execuete the init method after the dom has loaded.
**GOT IT WORKING - Hi I added var in front of the global var domRef and this seemed to fix the problem - could anyone explain why ? Also it see开发者_开发百科med I can use domRef with out declaring var however the variable above needed to be "1" we live and learn lol
function bnTalentFactory($){
if(bnTalentFactory.bnt)
return bnTalentFactory.bnt;
if(arguments.length == 0 || arguments[0] != jQuery)
var $ = jQuery;
var bnt = {},
privateVariable = 1,
domRef;
function privateMethod() {
// ...
}
bnt.jqueryIsDefined = function(){
return $ === jQuery;
}
bnt.moduleProperty = 1;
bnt.init = function () {
domRef = $("#pie").val();
alert("bingo" + domRef);
//domRef.hide();
};
bnTalentFactory.bnt = bnt;
return bnt;
}
var bnTalent = bnTalentFactory();
var anotherBnTalent = bnTalentFactory();
alert(bnTalent === anotherBnTalent);// true => the same instance
alert(bnTalent.jqueryIsDefined());// true => jquery is defined inside this object, withouth even passing it to the factory
Note that in order to have a valid "domRef", you need to execute this code after the dom is loaded, so that $("#pie")
exists at execution time.
This works: http://jsfiddle.net/J9PKB/ what exactly are you not able to do?
Edit
You're not using the init
method anywhere..., are you hoping it'll get call automatically? Because it won't. You have to call it yourself.
Add this on your head tag, after including your JS files:
<script type="text/javascript">
$(document).ready(function() { bnTalent.init(); } );
</script>
Let me know if this helps!
精彩评论