More questions about Javascript classes - javascript

I have tested quite a bit about making classes, now I finally discovered how it works, that's what I want to make class simple and clear, without spamming 'this'
The result is like that, now I only have 2 questions:
redsheep.options.show().sizes, is to call out this variable, now I think it is too long. How do I make it like redsheep.sizes?
redsheep.options.show().eat is not inherit from the sheepclass grass, and became undefined. How do I make default values for newly created objects?
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>A simple javascript function</title>
<script type="text/javascript">
$(document).ready(function(){
var sheepclass = function(options){
this.options = {'sizes' : 'thin',
'eat' : 'grass',
'color' : 'white',
show : function(){
return {'color':options.color,
'eat':options.eat,
'sizes':options.sizes
};
}
}
}
var blacksheep = new sheepclass({'color':'black'});
var redsheep = new sheepclass({'color':'red','sizes':'fat'});
$('div').append('<p>blackcsheep color : ' +
blacksheep.options.show().color);
$('div').append('<p>redsheep color : ' +
redsheep.options.show().color +
'<p>redsheep size:' +
redsheep.options.show().sizes +
'<p> redsheep eat:' +
redsheep.options.show().eat);
})
</script>
<style>
div{display:block;width:800px;height:400px;border:2px solid red;}
</style>
</head>
<body>
<div>
Result:
</div>
</body>
</html>

Adding a method to an object that returns its own properties is useless. Remove that and access the properties normally:
var sheepclass = function(options) {
this.options = $.extend({
'sizes': 'thin',
'eat': 'grass',
'color': 'white',
}, options);
}
You can access it like this:
redsheep.options.eat

Something like that would do:
var sheepclass = function(options) {
this.sizes = options.sizes || 'thin';
this.eat = options.eat || 'grass';
this.color = options.color || 'white';
}
That way, you can access properties directly (by using for example blacksheep.sizes):
var blacksheep = new sheepclass({'color':'black'});
console.log(blacksheep.sizes); // prints 'thin'

Related

Using library(element).function() or library.function() constructions in Javascript lib

We have Javascript library:
(function (global, factory) {
factory(global);
}(window , function() {
var MyLib = function(elem) {
return new MyLib.foo.init(elem);
}
MyLib.foo = {
init: function(elem) {
elem = typeof elem == 'string' ? window.document.getElementById(elem) : elem;
this[0] = elem;
return this;
},
test1: function() { // (1)
window.console.log('test1 ' + this[0].nodeName);
this[0].innerHTML = this[0].nodeName;
},
};
MyLib.foo.init.prototype = MyLib.foo;
MyLib.test2 = function() { // (2)
window.console.log('test2');
}
window.MyLib = window.ml = MyLib;
}));
function outerFunc(elem) {
ml(elem).test1();
ml.test2();
}
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript" src="example.js"></script>
<div onclick="outerFunc(this)">button</div>
</body>
</html>
When should we create functions like (1) and when like (2)?
Of course, if it needs to get an element, we would always use (1), like MyLib().myFunc(), am I right?
And for all situations, where an element is not affected, we should create (2) ,like MyLib.myFunc()?
May be we miss something with variables' protection?

SAPUI5 and dynamic URL for OData service

I am doing sample example using sapui5. I want to pass URL service dynamically and load ODATA service, but I really new with sapui5 and I don’t know how to do it.
This code below is what i tried to do but it is not working. Thanks a lot for your help.
createContent : function(oController) {
var oLayout = new sap.ui.commons.layout.AbsoluteLayout({width:"340px",height:"150px"});
oLayout.addStyleClass("CustomStyle"); //Add some additional styling for the border
var oLabel = new sap.ui.commons.Label({text:"Service Url"});
var oUrlInput = new sap.ui.commons.TextField({width:"190px"});
oLabel.setLabelFor(oUrlInput);
oLayout.addContent(oLabel, {right:"248px",top:"20px"});
oLayout.addContent(oUrlInput, {left:"110px",top:"20px"});
var oLabel = new sap.ui.commons.Label({text:"Service"});
var oSvcInput = new sap.ui.commons.TextField({width:"190px"});
oLabel.setLabelFor(oSvcInput);
oLayout.addContent(oLabel, {right:"248px",top:"62px"});
oLayout.addContent(oSvcInput, {left:"110px",top:"62px"});
var loadData =new sap.ui.commons.Button({
text : "load",
width:"133px",
press: function() {
oController.load();
}});
oLayout.addContent(loadData, {left:"110px",top:"104px"});
return oLayout;
}
// Controller
load: function(oEvent){
var url = sap.ui.getControl("oUrlInput").getValue();
var svc = sap.ui.getControl("oSvcInput").getValue();
var oModel = new sap.ui.model.odata.OdataModel(url + "/" + svc ,false);
var mylist = new sap.ui.model.ListBinding(oModel);
return mylist;
}
// index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons,sap.ui.table,sap.ui.ux3"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script>
sap.ui.localResources("simpleform");
var view = sap.ui.view({id:"idsimpleForm1", viewName:"simpleform.simpleForm", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
You have to give your controls an id to access them in the controller. Like this:
// create controls with id
var oLabel = new sap.ui.commons.Label("oLabelId", {text:"Service Url"});
var oUrlInput = new sap.ui.commons.TextField("oUrlInputId", {width:"190px"});
// then to get reference to the control later
var oLabel = sap.ui.getCore().byId("oLabelId");
var oUrlInput = sap.ui.getCore().byId("oUrlInputId");
Make sure, that you use the right Url:
var oModel = new sap.ui.model.odata.OdataModel("/sap/opu/odata/sap/" + svc ,false);
Make sure following.
Change the case of odataModel to ODataModel
Ensure the Service URL also correct
Obtain the reference of the control As described by kjokinen
Regards

Javascript not declaring variables

i'm new to JavaScript i have this script and i want to declare a variable on a if but on document.write , returns nothing what am i doing wrong ?
<head>
<script>
(function () {
setInterval(function () {
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
NetworkStatus.innerHTML = "Online";
NetworkStatus.className = "online";
var person="John Doe";
} else {
NetworkStatus.innerHTML = "Offline";
NetworkStatus.className = "offline";
var person="Santa Claus";
}
}, 100);
})();
</script>
</head>
<body>
<h1 id="status"></h1>
<script>
document.write(person + "<br>");
</script>
</body>
It's just all wrong, why use an IIFE and a timeout when all you have to do is add the script in the tag at the end of the DOM.
Also, you're setting the innerHTML of the element, and using document.write, which will overwrite the document ?
<head>
<title>I messed up</title>
</head>
<body>
<h1 id="status"></h1>
<script>
var NetworkStatus = document.getElementById("status"),
isOnline = navigator.onLine;
if (isOnline) {
var person = "John Doe";
NetworkStatus.innerHTML = "Online " + person;
NetworkStatus.className = "online";
} else {
var person = "Santa Claus";
NetworkStatus.innerHTML = "Offline " + person;
NetworkStatus.className = "offline";
}
</script>
</body>
You are in IIFE. which creates its own scope
And that's where it stays
Do this :
window.person="Santa Claus";
Instead of what you're doing.
var sets the scope of the variable to the function it is declared within. You are trying to document.write it from outside that function, so it is out of scope and inaccessible.
Use window.person instead of var person.
The function executes after 100ms which means the person variable has no value when the page loads.

Can't get Javascript to interact with Flash

I can't get my Javascript to affect my SWF object.
The object is rendered correctly in the browser but I cannot call the "fill" method that I exposed to the ExternalInterface.
The ready function "flashReady" is not called. Directly calling it from the console says that the flash object does not have the function "fill". Waiting for a while then calling the function does not help.
The error is TypeError: Object HTMLObjectElement has no method 'fill'
Actionscript code:
public class Main extends Sprite
{
public function Main() {
graphics.beginFill(0xff0000);
graphics.drawRect(0, 0, 200, 100);
graphics.endFill();
Security.allowDomain("*");
ExternalInterface.addCallback("fill", fill);
ExternalInterface.call("flashReady");
}
public function fill():void {
graphics.beginFill(0x00ff00);
graphics.drawRect(0, 0, 200, 100);
graphics.endFill();
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>
Flash UI Demo
</title>
<script type="text/javascript" src="swfobject.js">
</script>
<script type="text/javascript">
function flashReady() {
document.getElementById('AddCallbackExample').fill();
}
var swfVersionStr = "0";
var xiSwfUrlStr = "";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "always";
var attributes = {};
attributes.id = "AddCallbackExample";
attributes.name = "AddCallbackExample";
attributes.align = "middle";
swfobject.embedSWF(
"http://localhost:8001/swf", "flash",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
</script>
</head>
<body>
<div id="flash" />
</body>
</html>
Ok I figured it out, my version of the library didn't support allowDomain to take in "*" as an argument. I replaced it with "localhost" and it worked.

Grabbing Name attribute of Tags/Tag in Rally

I have been looking at the rally Object model, but I can't figure out how to grab the Name attribute of a Defect's Tag.
I made sure to include Tag and Tags in my fetch statement. I am storing all the defects into an array of objects called defectsNEWDEFECTS[]
I can return a Tag object by doing this:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags;
document.write(tagNEWDEFECTS);
which will return this:
[object Object]
But, I can't seem to get it to return the NAME of the tag.
I tried:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Tag.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tag.Name;
But they all return 'undefined'.
Any ideas how to get the name of a tag? Ultimately, the goal here is to have user-input custom tags that I can flag in my program to do certain things. For example, one tag will be named 'RollOverDefect'.
I need to be able to determine which Defects have a Tag called 'RollOverDefect'
Thanks!
Tags is a collection, so you'll ultimately need a nested loop over the Tags collection attribute to handle this. Once you've nested into an additional loop, you can reference the Tag Name via:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags[j].Name;
Hope this is helpful - let us know if that gets the job done.
You may find this example to be useful:
<html>
<head>
<title>App Example: Defects with Tags</title>
<meta name="Name" content="App Example: Defects with Tags" />
<meta name="Version" content="2013.2" />
<meta name="Vendor" content="Rally Labs" />
<script type="text/javascript" src="/apps/1.33/sdk.js?apiVersion=1.43""></script>
<script type="text/javascript">
var table = null;
function defectsWithTagsExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__'
);
function itemQuery() {
var queryObject = {
key: 'defects',
type: 'Defect',
fetch: 'FormattedID,Name,State,Description,Tags,Name',
query: '(State = "Submitted")'
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var tableDiv = document.getElementById('aDiv');
var config = {
'columnKeys' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnHeaders' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnWidths' : ['100px', '400px', '200px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.defects);
for (i=0;i<results.defects.length;i++) {
myDefect = results.defects[i];
myTags = results.defects[i].Tags;
myTagString = "";
for (j=0;j<myTags.length;j++) {
myTag = myTags[j];
myTagName = myTags[j].Name;
if (j == 0) {
myTagString += myTagName;
} else {
myTagString += ", " + myTagName;
}
}
linkConfig = {item: {FormattedID: myDefect.FormattedID, "_ref" : myDefect._ref}};
defectLink = new rally.sdk.ui.basic.Link(linkConfig);
table.setCell(i, 0, defectLink.renderToHtml());
table.setCell(i, 4, myTagString);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(defectsWithTagsExample);
</script>
</head>
<body>
<div id="aDiv"></div>
</body>
</html>

Categories

Resources