JavaScript module pattern not working - javascript

I am trying to implement module pattern in my code according to some examples online, what I am trying to achieve is to simply bind a button click event in my html to a function (which is not working), below is my HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script data-require="jquery#*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<input type="button" id="btn-msg" value="click me"/>
</body>
</html>
and here is my JS:
//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
}
Rutherford.Initiate = function() {
$("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
Rutherford.Initiate();
});
Here is as well a link to my plunker: http://plnkr.co/edit/tA94lzMPHkUOr8QuyJK8?p=preview
All what am trying to achieve is to bind the button to the function.

You need to call the anonymous function, not assign it. See the () below:
Rutherford.crud = (function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
}());
Here's an updated plunkr with this change: http://plnkr.co/edit/uiWHmtkMFEKywvFRk6DF?p=info

I believe that Evan Knowles wanted to say this:
//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = (function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
})( );
Rutherford.Initiate = function() {
$("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
Rutherford.Initiate();
});
This would work properly if you can use Rutherford as a Singleton.

Related

How to get this val(such as gLats in code) out of the function onComplete()?

This is the code that I want to work out, it's about AMap.com geolocation API. I want to know how to get this value (such as gLats in code) out of the function onComplete().
<!DOCTYPE html>
<html>
<head>
<title>amap</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=key"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id='container'></div>
<div id="tip"></div>
<div id="text"></div>
<div id="txt"></div>
<script type="text/javascript">
var map, geolocation;
map = new AMap.Map("", {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['succsee'];
var gLngs=data.position.getLng();
var gLats=data.position.getLat();
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
document.getElementById('text').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = 'failure';
}
</script>
</body>
</html>
As I can see, you are already accessing the needed values in onComplete():
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
You cannot simply get them, onComplete is a callback that is called when the values are available. So do anything about them in onComplete, you may want to assingn them to global variables, etc, to have them easyly accessible from anywhere in code.
Assigning them to globals is the way to go.
//declare in the global scope
var gLats = null;
var gLngs = null;
...
function onComplete(data)
{
var str=['success'];
gLats=data.position.getLat();
gLngs=data.position.getLng();
...
}

How to use namespace JavaScript?

Hi I am trying to call the namespace JavaScript which is given in the internal JavaScript in below HTML representation.
<head>
<script type="text/javascript">
var ns = {
sampleAlert : function() {
ns.message(var );
}
message :function(var ) {
alert('msg');
}
}
</script>
</head>
<body>
<!--how to call the function sampleAlert-->
</body>
Is that possible? I am not able to call that namespace JavaScript function in the body.
Call it like this:
ns.sampleAlert();
Read this link to have more understanding on JavaScript Namespace
You probably need to do something like the following.
<head>
<script type="text/javascript">
var ns = {
sampleAlert : function(messageText) {
ns.message(messageText);
},
message : function(text) {
alert('msg ' + text);
}
}
</script>
</head>
<body>
<!--how to call the function sampleAlert-->
<script type="text/javascript">
ns.sampleAlert("this text will be displayed in the alert");
</script>
</body>

Why can I call function which is in a shadow dom?

I created a custom element called "memory-box" like the below code.
Please pay attention to the function "logthis" which is in "memory-box-template".
memory-box.html
<template id="memory-box-template">
<input id="memory-box" type="form" />
<input type="button" id="testbutton" />
<script type="text/javascript">
function logthis(me){
console.log(me);
}
</script>
</template>
<script type="text/javascript">
(function() {
var thisDoc = document.currentScript.ownerDocument;
var storage = localStorage;
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var temp = thisDoc.querySelector('#memory-box-template');
var con = document.importNode(temp.content, true);
this.createShadowRoot().appendChild(con);
var input = this.querySelector('::shadow #memory-box');
var data = storage.getItem(this.id);
input.value = data;
input.addEventListener('input', saveData.bind(input, this.id));
}
},
});
document.registerElement('memory-box', {
prototype: proto
});
function saveData(id, e) {
storage.setItem(id, this.value);
}
})();
</script>
Now, I uses the custom element "memory-box" like the below code.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="import" href="/html/memory-box.html">
</head>
<body>
<div><memory-box id="memory1"></memory-box></div>
<div><memory-box id="memory2"></memory-box></div>
<div><memory-box id="memory3"></memory-box></div>
<div><memory-box id="memory4"></memory-box></div>
</body>
<script type="text/javascript">
logthis(this);
</script>
</html>
As you can see, I putted a script in the index.html and called the function "logthis" just because I was curious. And no error occurred.
Why?
The function "logthis" is in each shadow doms. It's supposed not able to be called outside the shadow dom, I think.
As explained here, while the HTML within Shadow DOM is encapsulated, any JavaScript is NOT -- it is in the global scope, unless you utilize specific javascript techniques (namescaping, IIFE) to do so.
Hope this helps,
Jonathan Dodd

How to pass div ids to javascript at onload?

I have an Html file like this:
<!doctype html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style/boxClass.css" />
<script type="text/javascript">
/* lightBox class */
function box (id1,id2) {
this.boxBackgroundDiv = document.getElementById (id1);
this.boxWorkAreaDiv = document.getElementById (id2);
}
lightBox.prototype.setBackgroundColor = function(c) {
this.boxBackgroundDiv.style.backgroundColor = c;
alert('Hello back');
};
function init (id1,id2)
{
boxObj = new box (id1,id2);
alert ("Hello");
}
</script>
</head>
<body onload="init('box1','box2')">
<div id="lightbox1" class="boxBackground">I am here</div>
<div id="lightbox2" class="boxWorkArea"><button onclick="boxObj.setBackgroundColor('Red')">I am here</button></div>
</body>
</html>
Now when I call my init function the way it is in this code via it works fine. But if I do as below via window.onload, it does not work. its not able to get the div ids in this case. But I need div ids to crate objs for my class.
<!doctype html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style/boxClass.css" />
<script type="text/javascript">
/* lightBox class */
function box (id1,id2) {
this.boxBackgroundDiv = document.getElementById (id1);
this.boxWorkAreaDiv = document.getElementById (id2);
}
lightBox.prototype.setBackgroundColor = function(c) {
this.boxBackgroundDiv.style.backgroundColor = c;
alert('Hello back');
};
function init (id1,id2)
{
boxObj = new box (id1,id2);
alert ("Hello");
}
window.onload = init ("box1",box2);
</script>
</head>
<body>
<div id="lightbox1" class="boxBackground">I am here</div>
<div id="lightbox2" class="boxWorkArea"><button onclick="boxObj.setBackgroundColor('Red')">I am here</button></div>
</body>
</html>
Two issues:
1) You are missing quotes around box2 parameter,
2) You are assigning the return value of init function (which here is a void) to window.onload handler.
You should assign the onload handler as below:
window.onload = function(){
init ("box1","box2");
}

javascript basic objects / functions

i tried to pop an alert when clicked on a div , didn't really succeed , i messed it a little to practice with objects.
here is the the code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var mine = {
var start = {
modeBox : function(){
alert();
}
}
}
</script>
</head>
<body>
<div id="askMode" onclick="mine.start.modeBox();">My mine</div>
</body>
</html>
the problem : not alerting
why i don't get alert when i click on the div?
live example : http://jsfiddle.net/YqP93/
The following code tested in Firefox and Chrome:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var mine = {
start: {
modeBox : function(){
alert('Test');
}
}
}
</script>
</head>
<body>
<div id="askMode" onclick="mine.start.modeBox();">My mine</div>
</body>
</html>
NOTE: the code you posted in jsfiddle is not working, but you can copy and paste the code above that works in browsers mentioned.
this.mine = {
start: {
modeBox : function(){
alert();
}
}
you are trying to declare a var in an object literal. I don't think this is valid js for one but more importantly you can not get at vars declared in that scope. You have to assign the property to the object. You had it right with the modeBox.
Get rid of the var deceleration (why?):
mine = {
start: {
modeBox: function() {
alert();
}
}
};
Demo: http://jsfiddle.net/YqP93/3/
try this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var mine = {
start: {
modeBox: function(){
alert();
}
}
}
</script>
</head>
<body>
<div id="askMode" onclick="mine.start.modeBox();">My mine</div>
</body>
</html>

Categories