Javascript module programming - javascript

I'm study module programming.
take a look at below code:
var goodsspec = function(){
function setSpec(){
var
_price,
_storage,
defaultstats = true,
_val = '',
_resp = {
storage:".goods_stock",
price:".price"
}
$(".sys_item_spec .sys_item_specpara").each(function(){
var i = $(this);
var v = i.attr("data-attrval");
if(!v){
defaultstats = false;
}else{
val += _val!=""?"":"";
_val += v;
}
});
if(!!defaultstats){
_storage = sys_item['sys_attrprice'][_val]['goods_storage'];
_price = sys_item['sys_attrprice'][_val]['price'];
}else{
_storage = sys_item['goods_storage'];
_price = sys_item['price'];
}
$(_resp.storage).text( _storage);
$(_resp.price).text( _price);
if ( _storage == 0){
// Waring
}
}
return {
set:function(){
return setSpec();
}
};
}();
console.log(goodsspec.price);
I want to get _price and storage property value _value when I selected item.
How can I do this?

try something like
var Item = new Object();
function setSpec(){
// setting code
Item.price = _price;
Item.storage = _storage
}
then you could use
console.log("Prices is "+Item.price+" for "+Item.storage+".");

Related

JavaScript array has elements but length is zero

I've done some searching around the web and nothing seems to solve my problem. I have the following jQuery code:
function youtube_data_parser(data) {
//---> parse video data - start
var qsToJson = function(qs) {
var res = {};
var pars = qs.split('&');
var kv, k, v;
for (i in pars) {
kv = pars[i].split('=');
k = kv[0];
v = kv[1];
res[k] = decodeURIComponent(v);
}
return res;
}
//---> parse video data - end
var get_video_info = qsToJson(data);
if (get_video_info.status == 'fail') {
return {
status: "error",
code: "invalid_url",
msg: "check your url or video id"
};
} else {
// remapping urls into an array of objects
//--->parse > url_encoded_fmt_stream_map > start
//will get the video urls
var tmp = get_video_info["url_encoded_fmt_stream_map"];
if (tmp) {
tmp = tmp.split(',');
for (i in tmp) {
tmp[i] = qsToJson(tmp[i]);
}
get_video_info["url_encoded_fmt_stream_map"] = tmp;
}
//--->parse > url_encoded_fmt_stream_map > end
//--->parse > player_response > start
var tmp1 = get_video_info["player_response"];
if (tmp1) {
get_video_info["player_response"] = JSON.parse(tmp1);
}
//--->parse > player_response > end
//--->parse > keywords > start
var keywords = get_video_info["keywords"];
if (keywords) {
key_words = keywords.replace(/\+/g, ' ').split(',');
for (i in key_words) {
keywords[i] = qsToJson(key_words[i]);
}
get_video_info["keywords"] = {
all: keywords.replace(/\+/g, ' '),
arr: key_words
};
}
//--->parse > keywords > end
//return data
return {
status: 'success',
raw_data: qsToJson(data),
video_info: get_video_info
};
}
}
function getVideoInfo() {
var get_video_url = $('#ytdlUrl').val();
var get_video_id = getUrlVars(get_video_url)['v'];
var video_arr_final = [];
var ajax_url = "video_info.php?id=" + get_video_id;
$.get(ajax_url, function(d1) {
var data = youtube_data_parser(d1);
var video_data = data.video_info;
var player_info = data.video_info.player_response;
var video_title = player_info.videoDetails.title.replace(/\+/g, ' ');
var fmt_list = video_data.fmt_list.split(',');
var video_thumbnail_url = video_data.thumbnail_url;
var video_arr = video_data.url_encoded_fmt_stream_map;
//create video file array
$.each(video_arr, function(i1, v1) {
var valueToPush = {};
valueToPush.video_url = v1.url;
valueToPush.video_thumbnail_url = video_thumbnail_url;
valueToPush.video_title = video_title;
$.each(fmt_list, function(i2, v2) {
var fmt = v2.split('/');
var fmt_id = fmt[0];
var fmt_quality = fmt[1];
if (fmt_id == v1.itag) {
valueToPush.fmt_id = fmt_id;
valueToPush.fmt_quality = fmt_quality;
}
});
video_arr_final.push(valueToPush);
});
});
return video_arr_final;
}
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function fillInOptions(ytOptions) {
//console.log(ytOptions);
//alert(ytOptions[0]);
var ytFill = ytOptions;
console.log(ytFill);
//ytFill.forEach(function(i,v) {
var ytdlOptions = $('#ytdlOptions');
ytFill.forEach(function(i,v) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
return true;
}
function showYTDLLoader() {
$('#ytdlInput').fadeOut(1000, function() {
$('#ytdlLoader').fadeIn(500);
});
var options = getVideoInfo();
//console.log(options);
if (fillInOptions(options) == true) {
//do rest
}
}
function showYTDLOptions() {
return true;
}
function startDownload() {
showYTDLLoader();
}
function hideYTDLLoader() {
$('#ytdlLoader').fadeOut(500);
}
function animateCSS(element, animationName, callback) {
const node = $(element);
node.addClass(animationName);
function handleAnimationEnd() {
node.removeClass(animationName);
node.animationend = null;
if (typeof callback === 'function') callback();
}
node.animationend = handleAnimationEnd();
}
When my button is clicked, I call showYTDLLoader() which gets an array of objects from the YouTube API that looks like this:
[
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&ratebypass=yes&dur=917.768&lmt=1572418007364260&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5535432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAIp-4gyUTLoXFetbY0ha_YnR7DJqsp_MNjjIxqDdfPZJAiEA_WPd21jgX9broBcigf8rcSEVoJb2_NX7t3XZQqytsSM%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "22",
"fmt_quality": "1280x720"
},
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=18&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&gir=yes&clen=44248820&ratebypass=yes&dur=917.768&lmt=1572416976690256&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5531432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRQIhANTZJlBHFWQWCnfK11yvLiPUV26c6NzvqIMKjDwmsByMAiBUSy0ZJMo4GdHSiRU4xBDDLxLtzwKZAqAKCiB-1aViDQ%3D%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "18",
"fmt_quality": "640x360"
}
]
But when I try and loop through each entry with fillInOptions(), my loop is never completed because the length is apparently zero. However, when I dump the array using console.log() it tells me the length is 2, and displays the above. I need to be able to add each option to my dropdown.
Thankyou!
UPDATE: Added full code, sorry!
It looks like your .forEach() is the root of the problem. The parameters of a forEach are currentValue, index like this: array.forEach(function(currentValue, index) {}); but it looks like you're using them in the opposite way
Try rewriting that iteration to this:
ytFill.forEach(function(v, i) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
Notice the difference in the order of v and i in the parameters.

How can I refresh or load JSON to my viewModel on Knockout JS with complex models

I fork the code from here:
http://kindohm.github.io/knockout-query-builder/
The code works nice on the client side.
But when I try to save the viewModel as JSON and then retrieve the data from the server the UI never refresh at all.
This is the original viewModel:
window.QueryBuilder = (function(exports, ko){
var Group = exports.Group;
function ViewModel() {
var self = this;
self.group = ko.observable(new Group());
// the text() function is just an example to show output
self.text = ko.computed(function(){
return self.group().text();
});
}
exports.ViewModel = ViewModel;
return exports;
})(window.QueryBuilder || {}, window.ko);
I be added the next method to the viewModel
self.Save = function () {
console.log(ko.toJSON(self));
}
Added this button to the view
<input type="submit" value="Save" data-bind="click: Save"/>
This is the Group viewModel:
window.QueryBuilder = (function(exports, ko){
var Condition = exports.Condition;
function Group(data){
var self = this;
self.templateName = data.templateName;
self.children = ko.observableArray(data.children);
self.logicalOperators = ko.observableArray(data.logicalOperators);
self.selectedLogicalOperator = ko.observable(data.selectedLogicalOperator);
// give the group a single default condition
self.children.push(new Condition());
self.addCondition = function(){
self.children.push(new Condition());
};
self.addGroup = function(){
self.children.push(new Group());
};
self.removeChild = function(child){
self.children.remove(child);
};
// the text() function is just an example to show output
self.text = ko.computed(function(){
var result = '(';
var op = '';
for (var i = 0; i < self.children().length; i++){
var child = self.children()[i];
console.log(child);
result += op + child.text();
op = ' ' + self.selectedLogicalOperator() + ' ';
}
return result += ')';
});
}
exports.Group = Group;
return exports;
})(window.QueryBuilder || {}, window.ko);
So when I press the "save" button the console show the JSON from this viewModel, everything fine here.
This is the JSON returned:
{"group":{"templateName":"group-template","children":[{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"}],"logicalOperators":["AND","OR"],"selectedLogicalOperator":"AND","text":"(Points = 0 AND Points = 0 AND Points = 0)"},"text":"(Points = 0 AND Points = 0 AND Points = 0)"}
I make a simple hack to avoid the connection to the server, so I take that json copy and paste on the load event and send to the constructor of the viewModel:
var vm;
window.addEventListener('load', function(){
var json = {"group":{"templateName":"group-template","children":[{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"},{"templateName":"condition-template","fields":["Points","Goals","Assists","Shots","Shot%","PPG","SHG","Penalty Mins"],"selectedField":"Points","comparisons":["=","<>","<","<=",">",">="],"selectedComparison":"=","value":0,"text":"Points = 0"}],"logicalOperators":["AND","OR"],"selectedLogicalOperator":"AND","text":"(Points = 0 AND Points = 0 AND Points = 0)"},"text":"(Points = 0 AND Points = 0 AND Points = 0)"};
vm = new QueryBuilder.ViewModel(json);
ko.applyBindings(vm);
}, true);
Then I modify the viewModel to recibe the json parameter
window.QueryBuilder = (function(exports, ko){
var Group = exports.Group;
function ViewModel(json) {
var self = this;
self.group = ko.observable(json.group);
// the text() function is just an example to show output
self.text = ko.computed(function(){
return self.group().text();
});
self.Save = function () {
console.log(ko.toJSON(self));
}
}
exports.ViewModel = ViewModel;
return exports;
})(window.QueryBuilder || {}, window.ko);
When I refresh the index.html the view is never loaded correctly and show this error on the JS console:
TypeError: self.group(...).text is not a function
return self.group().text();
Someone knows where is my mistake?
The last problem I had was related to the text() function on the child.
I fix this with the use of try/catch. So when the viewModel are new it have the text() function, but when this is loadad the text() does not exist, so I take the value directly from the "text" field.
try {
result += op + child.text();
}
catch(err) {
result += op + child.text;
}
The problem was on the Group class and Condition class.
This is the current and working code:
window.QueryBuilder = (function(exports, ko){
var Condition = exports.Condition;
function Group(data){
var self = this;
self.templateName = data.templateName;
self.children = ko.observableArray(data.children);
self.logicalOperators = ko.observableArray(data.logicalOperators);
self.selectedLogicalOperator = ko.observable(data.selectedLogicalOperator);
// give the group a single default condition
self.children.push(new Condition(data.children[0]));
self.addCondition = function(){
self.children.push(new Condition());
};
self.addGroup = function(){
self.children.push(new Group());
};
self.removeChild = function(child){
self.children.remove(child);
};
// the text() function is just an example to show output
self.text = ko.computed(function(){
var result = '(';
var op = '';
for (var i = 0; i < self.children().length; i++){
var child = self.children()[i];
try {
result += op + child.text();
}
catch(err) {
result += op + child.text;
}
op = ' ' + self.selectedLogicalOperator() + ' ';
}
return result += ')';
});
}
exports.Group = Group;
return exports;
})(window.QueryBuilder || {}, window.ko);
window.QueryBuilder = (function(exports, ko){
function Condition(data){
var self = this;
self.templateName = data.templateName;
self.fields = ko.observableArray(data.fields);
self.selectedField = ko.observable(data.selectedField);
self.comparisons = ko.observableArray(data.comparisons);
self.selectedComparison = ko.observable(data.selectedComparison);
self.value = ko.observable(data.value);
// the text() function is just an example to show output
self.text = ko.computed(function(){
return self.selectedField() +
' ' +
self.selectedComparison() +
' ' +
self.value();
});
}
exports.Condition = Condition;
return exports;
})(window.QueryBuilder || {}, window.ko);
Instead of self.group = ko.observable(json.group);, you should take a similar approach as you did on load self.group = ko.observable(new Group());, but this time pass the json.group data in Group
self.group = ko.observable(new Group(json.group));
I don't see where Group is defined, but you should make sure that it is able to handle and convert the JSON you now pass in, into observables.

remove onclick function and change to onload or document.ready

What would be the easiest way to remove the onclick event from this script?
The script below uses google translate to translate from one language to another.
I want to be able to set the language to a
Request.Form("language")
so when I submit a form it will set the language. (I can do this so it is not a problem, however once this language is set I want the script to automatically translate the text.
something like
<body onload="">
or
document.ready or
translate.ready
However I am not 100% sure how to do this:
<script type='text/javascript'>
google.load("language", "1");
var translator = false;
function init(){
var str = $("source").innerHTML;
var triggerCollection = $("langSelect").select("li");
triggerCollection.invoke("observe", "click", handleTriggerClick);
translator = new Translator("source", "p,ul");
translator.addEventListener("complete", function(obj){
//console.log("The translation has finished %o", obj);
{
document.form1.g_content_text.value = $("source").innerHTML;
}{
//document.form1.submit();
}
});
translator.addEventListener("begin", function(obj){
//console.log("Translation has begun! %o", obj);
});
//console.log(translator.textNodeCollection);
}
function handleTriggerClick(e){
var lang = e.element().getAttribute("lang"); // This is the language to translate to!
var str = $("source").innerHTML;
translator.translate(lang);
}
function insertToForeign(obj){
$("display").innerHTML = obj.translation;
}
google.setOnLoadCallback(init);
var Translator = Class.create(EventDispatcher, {
initialize : function(element, selector, config){
this.element = $(element);
this.preservedHTML = this.element.innerHTML;
this.config = Object.extend(this.getDefaultConfig(), config);
this.textNodeCollection = this.collectChildren(selector);
this.preservedParentHash = {};
this.placeHolderHash = {};
this.entityWasher = new Element("div");
this.textNodeCollection = this.textNodeCollection.findAll(this.purifyTextNode);
},
purifyTextNode : function(node){
try{
if(!node)
return false;
return node.nodeType == 3;
}
catch(e){
return false;
}
},
getDefaultConfig : function(){
return { maxLength : 1000, srcLang : "en", recursive : true, type : "text" };
},
collectChildren : function(selector){
return this.element.select(selector).collect(this.collectTextNodes.bind(this)).flatten();
},
collectTextNodes : function(element){
var self = this;
var stack = $A(element.childNodes).collect(function(child){
if(child.nodeType == 3 && child.nodeValue.length < self.config.maxLength && child.nodeValue.search(/^\s+$/g) == -1)
return child;
else if(child.nodeType == 3 && child.nodeValue.length > self.config.maxLength)
return self.splitTextNode(child);
else if(child.nodeType == 1 && self.config.recursive)
return self.collectTextNodes(child);
});
return stack;
},
splitStringByMax : function(text){
var offset = 0;
var textArr = [];
while(text.length > this.config.maxLength){
var tmp = text.substr(0, this.config.maxLength);
offset = tmp.lastIndexOf(" ");
var subText = text.substr(0, offset);
text = text.substr(offset);
textArr.push(subText);
}
textArr.push(text);
return textArr;
},
splitTextNode : function(node){
var nodeStack = [];
var textArr = this.splitStringByMax(node.nodeValue);
var prevNode = false;
textArr.each(function(text, itr){
var newNode = document.createTextNode(text);
nodeStack.push(newNode);
if(node.nextSibling != null && !prevNode)
node.parentNode.insertBefore(newNode, node.nextSibling);
else if(prevNode && prevNode.nextSibling != null)
node.parentNode.insertBefore(newNode, prevNode.nextSibling);
else
node.parentNode.appendChild(newNode);
prevNode = newNode;
});
node.parentNode.removeChild(node);
return nodeStack;
},
getEventBeginObject : function(destLang){
return {
destLang : destLang,
srcLang : this.config.srcLang,
srcLangNodes : this.textNodeCollection,
srcHTML : this.preservedHTML
}
},
getEventCompleteObject : function(result){
return {
srcLangNodes : this.textNodeCollection,
destLangNodes : this.translationStack,
destLangHTML : this.element.innerHTML,
srcLangHTML : this.preservedHTML,
result : result,
resultStack : this.resultStack
}
},
finishTranslation : function(result){
this.translating = false;
this.dispatchEvent("complete", this.getEventCompleteObject(result));
},
translate : function(destLang){
if(this.translating)
return false;
var self = this;
this.dispatchEvent("begin", this.getEventBeginObject(destLang));
this.textNodeCount = this.textNodeCollection.length;
this.translationStack = [];
this.resultStack = [];
this.textNodeCollection.each(function(node, index){
self.translating = true;
google.language.translate(node.nodeValue, self.config.srcLang, destLang, self.handleTranslation.bind(self, node, index));
});
return true;
},
getPreservedParent : function(node, index){
if(this.preservedParentHash[index])
return this.preservedParentHash[index];
return this.preservedParentHash[index] = node.parentNode;
},
getPlaceHolder : function(index){
return this.placeHolderHash[index] || false;
},
setPlaceHolder : function(node, index){
this.placeHolderHash[index] = node;
},
handleTranslation : function(node, index, obj){
try{
var parent = this.getPreservedParent(node, index);
this.entityWasher.innerHTML = obj.translation;
var translatedText = this.entityWasher.innerHTML;
if(node.nodeValue.search(/^\s/) > -1)
translatedText = " " + translatedText;
if(node.nodeValue.search(/\s$/) > -1)
translatedText = translatedText + " ";
var newText = document.createTextNode(translatedText);
if(this.getPlaceHolder(index))
parent.replaceChild(newText, this.getPlaceHolder(index));
else
parent.replaceChild(newText, node);
this.setPlaceHolder(newText, index);
this.translationStack.push(newText);
this.resultStack.push(obj);
this.textNodeCount--;
if(this.textNodeCount <= 0)
this.finishTranslation(obj);
}
catch(e){
console.log("Error has occured with handling translation error = %o arguments = %o", e, arguments);
}
}
});
</script>
if you click on the li it sets the language and start the function:
<ul id="langSelect">
<li lang="de">German</li></ul>
another solution might be to similate a user click on the li command, but I am also not sure how to do this!
Any help would be appreciated.
Any help would be appreciated
I think part of the problem lies here:
triggerCollection.invoke("observe", "click", handleTriggerClick);
It sounds like you are interested in the dom:loaded event.
document.observe("dom:loaded", function() {
translator.translate($('langselect').getAttribute('lang'));
});
Or if you know the language code you can feed it in directly. For the german example:
translator.translate('de');

javascript - Failed to load source for: http://localhost/js/m.js

Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.

how to change javascript function to ActionScript 3?

anybody can help me to change that javascript function to AS3?
thanks :)
function parseURLtoVars(strLocation){
var rArray = new Array();
var key;
var urlString = new String(strLocation);
if (urlString.search(/\?/)>-1){
var qArray = urlString.split('?')[1].split('&');
if (qArray.length > 0){
for (key in qArray){
var arVal = qArray[key].split('=');
if (arVal.length ==2){
rArray[arVal[0]] = arVal[1];
} else {
continue;
}
}
return rArray;
} else {
return false;
}
}
return false;
}
How about
private function parseURLtoVars(strLocation:String):*
{
var rArray:Array = new Array();
var key:String;
var urlString:String = new String(strLocation);
if (urlString.search(/\?/)>-1){
var qArray:Array = urlString.split('?')[1].split('&');
if (qArray.length > 0){
for (key in qArray){
var arVal:Array = qArray[key].split('=');
if (arVal.length ==2){
rArray[arVal[0]] = arVal[1];
} else {
continue;
}
}
return rArray;
} else {
return false;
}
}
return false;
}
this returns params as an object, to return a boolean should be a simple edit.
function getParams(documentRoot):Object
{
try {
var params:Object = LoaderInfo(documentRoot.loaderInfo).parameters;
var pairs:Object = {};
var key:String;
for(key in params) {
pairs.key = String(params.key);
}
} catch(e:Error) {
return {};
}
return params;
}
I believe you just have to add type definitions to your function and variables.
So:
function parseURLtoVars(strLocation):Array
{
var rArray:Array = new Array();
var urlString:String = new String(strLocation);
...
for(var key:String in qArray)
...
return rArray;
} else {
return null;
}
}
return null;
}
I set the return of false to be nulls, but you can change your function return type to Object so you can return anything out of it, but I assumed you wanted an array to be returned.
It's not exactly what you asked, but in AS 3 I think there's an easier way:
import flash.net.URLVariables;
private function parseURLtoVars(strLocation:String):URLVariables {
strLocation = strLocation.indexOf("?") != -1 ? strLocation.split("?")[1] : strLocation;
return new URLVariables(strLocation);
}
And you could use it like this:
var testUrl:String = "test.php?key=value&key2=another_value";
var urlVars:URLVariables = parseURLtoVars(testUrl);
for(var k:String in urlVars) {
trace(k + " = " + urlVars[k]);
}

Categories

Resources