You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by fi...@apache.org on 2012/04/27 22:52:58 UTC

js commit: [CB-588] Removed instanceof and added typecheck helper functions isDate and isArray to utils module. Also added tests to make sure non-functions passed into channel subscribe method throws exceptions

Updated Branches:
  refs/heads/master 140008f08 -> f9f51d941


[CB-588] Removed instanceof and added typecheck helper functions isDate and isArray to utils module. Also added tests to make sure non-functions passed into channel subscribe method throws exceptions


Project: http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/commit/f9f51d94
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/tree/f9f51d94
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/diff/f9f51d94

Branch: refs/heads/master
Commit: f9f51d9410e0162ee6ff4bdd7cbadbbe3464ebbc
Parents: 140008f
Author: Fil Maj <ma...@gmail.com>
Authored: Fri Apr 27 13:55:20 2012 -0700
Committer: Fil Maj <ma...@gmail.com>
Committed: Fri Apr 27 13:55:20 2012 -0700

----------------------------------------------------------------------
 lib/blackberry/plugin/blackberry/Contact.js      |   22 +++---
 lib/blackberry/plugin/blackberry/ContactUtils.js |    5 +-
 lib/blackberry/plugin/blackberry/contacts.js     |    7 +-
 lib/common/channel.js                            |   55 +++++++++--------
 lib/common/plugin/Contact.js                     |    6 +-
 lib/common/plugin/FileTransfer.js                |    2 +-
 lib/common/plugin/contacts.js                    |    5 +-
 lib/common/utils.js                              |   26 +++-----
 lib/cordova.js                                   |    2 +-
 lib/ios/exec.js                                  |    2 +-
 test/test.channel.js                             |   26 +++++++-
 11 files changed, 91 insertions(+), 67 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/blackberry/plugin/blackberry/Contact.js
----------------------------------------------------------------------
diff --git a/lib/blackberry/plugin/blackberry/Contact.js b/lib/blackberry/plugin/blackberry/Contact.js
index b37bde0..d053c6d 100644
--- a/lib/blackberry/plugin/blackberry/Contact.js
+++ b/lib/blackberry/plugin/blackberry/Contact.js
@@ -1,5 +1,6 @@
 var ContactError = require('cordova/plugin/ContactError'),
     ContactUtils = require('cordova/plugin/blackberry/ContactUtils'),
+    utils = require('cordova/utils'),
     ContactAddress = require('cordova/plugin/ContactAddress'),
     exec = require('cordova/exec');
 
@@ -19,8 +20,7 @@ var findByUniqueId = function(uid) {
     if (!uid) {
         return null;
     }
-    var bbContacts = blackberry.pim.Contact
-            .find(new blackberry.find.FilterExpression("uid", "==", uid));
+    var bbContacts = blackberry.pim.Contact.find(new blackberry.find.FilterExpression("uid", "==", uid));
     return bbContacts[0] || null;
 };
 
@@ -101,7 +101,7 @@ var saveToDevice = function(contact) {
     // NOTE: BlackBerry's Date.parse() does not work well, so use new Date()
     //
     if (contact.birthday !== null) {
-        if (contact.birthday instanceof Date) {
+        if (utils.isDate(contact.birthday)) {
             bbContact.birthday = contact.birthday;
         } else {
             var bday = contact.birthday.toString();
@@ -110,7 +110,7 @@ var saveToDevice = function(contact) {
     }
 
     // BlackBerry supports three email addresses
-    if (contact.emails && contact.emails instanceof Array) {
+    if (contact.emails && utils.isArray(contact.emails)) {
 
         // if this is an update, re-initialize email addresses
         if (update) {
@@ -138,7 +138,7 @@ var saveToDevice = function(contact) {
 
     // BlackBerry supports a finite number of phone numbers
     // copy into appropriate fields based on type
-    if (contact.phoneNumbers && contact.phoneNumbers instanceof Array) {
+    if (contact.phoneNumbers && utils.isArray(contact.phoneNumbers)) {
 
         // if this is an update, re-initialize phone numbers
         if (update) {
@@ -186,7 +186,7 @@ var saveToDevice = function(contact) {
 
     // BlackBerry supports two addresses: home and work
     // copy the first two addresses found from Contact
-    if (contact.addresses && contact.addresses instanceof Array) {
+    if (contact.addresses && utils.isArray(contact.addresses)) {
 
         // if this is an update, re-initialize addresses
         if (update) {
@@ -199,7 +199,7 @@ var saveToDevice = function(contact) {
         var bbWorkAddress = null;
         for ( var k = 0; k < contact.addresses.length; k += 1) {
             address = contact.addresses[k];
-            if (!address || address instanceof ContactAddress === false) {
+            if (!address || address.id === undefined || address.pref === undefined || address.type === undefined || address.formatted === undefined) {
                 continue;
             }
 
@@ -214,7 +214,7 @@ var saveToDevice = function(contact) {
     }
 
     // copy first url found to BlackBerry 'webpage' field
-    if (contact.urls && contact.urls instanceof Array) {
+    if (contact.urls && utils.isArray(contact.urls)) {
 
         // if this is an update, re-initialize web page
         if (update) {
@@ -236,7 +236,7 @@ var saveToDevice = function(contact) {
 
     // copy fields from first organization to the
     // BlackBerry 'company' and 'jobTitle' fields
-    if (contact.organizations && contact.organizations instanceof Array) {
+    if (contact.organizations && utils.isArray(contact.organizations)) {
 
         // if this is an update, re-initialize org attributes
         if (update) {
@@ -258,7 +258,7 @@ var saveToDevice = function(contact) {
     }
 
     // categories
-    if (contact.categories && contact.categories instanceof Array) {
+    if (contact.categories && utils.isArray(contact.categories)) {
         bbContact.categories = [];
         var category = null;
         for ( var o = 0; o < contact.categories.length; o += 1) {
@@ -274,7 +274,7 @@ var saveToDevice = function(contact) {
 
     // invoke native side to save photo
     // fail gracefully if photo URL is no good, but log the error
-    if (contact.photos && contact.photos instanceof Array) {
+    if (contact.photos && utils.isArray(contact.photos)) {
         var photo = null;
         for ( var p = 0; p < contact.photos.length; p += 1) {
             photo = contact.photos[p];

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/blackberry/plugin/blackberry/ContactUtils.js
----------------------------------------------------------------------
diff --git a/lib/blackberry/plugin/blackberry/ContactUtils.js b/lib/blackberry/plugin/blackberry/ContactUtils.js
index 848a601..28dc9e1 100644
--- a/lib/blackberry/plugin/blackberry/ContactUtils.js
+++ b/lib/blackberry/plugin/blackberry/ContactUtils.js
@@ -2,6 +2,7 @@ var ContactAddress = require('cordova/plugin/ContactAddress'),
     ContactName = require('cordova/plugin/ContactName'),
     ContactField = require('cordova/plugin/ContactField'),
     ContactOrganization = require('cordova/plugin/ContactOrganization'),
+    utils = require('cordova/utils'),
     Contact = require('cordova/plugin/Contact');
 
 /**
@@ -153,7 +154,7 @@ module.exports = {
 
         // build a filter expression using all Contact fields provided
         var filterExpression = null;
-        if (fields && fields instanceof Array) {
+        if (fields && utils.isArray(fields)) {
             var fe = null;
             for ( var f in fields) {
                 if (!fields[f]) {
@@ -213,7 +214,7 @@ module.exports = {
         var contact = new Contact(bbContact.uid, bbContact.user1);
 
         // nothing to do
-        if (!fields || !(fields instanceof Array) || fields.length === 0) {
+        if (!fields || !(utils.isArray(fields)) || fields.length === 0) {
             return contact;
         } else if (fields.length == 1 && fields[0] === "*") {
             // Cordova enhancement to allow fields value of ["*"] to indicate

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/blackberry/plugin/blackberry/contacts.js
----------------------------------------------------------------------
diff --git a/lib/blackberry/plugin/blackberry/contacts.js b/lib/blackberry/plugin/blackberry/contacts.js
index a0b0c42..8edfa51 100644
--- a/lib/blackberry/plugin/blackberry/contacts.js
+++ b/lib/blackberry/plugin/blackberry/contacts.js
@@ -1,4 +1,5 @@
 var ContactError = require('cordova/plugin/ContactError'),
+    utils = require('cordova/utils'),
     ContactUtils = require('cordova/plugin/blackberry/ContactUtils');
 
 module.exports = {
@@ -15,8 +16,8 @@ module.exports = {
         }
 
         // Search qualifier is required and cannot be empty.
-        if (!fields || !(fields instanceof Array) || fields.length === 0) {
-            if (typeof fail === 'function') {
+        if (!fields || !(utils.isArray(fields)) || fields.length === 0) {
+            if (typeof fail == 'function') {
                 fail(new ContactError(ContactError.INVALID_ARGUMENT_ERROR));
             }
             return;
@@ -59,4 +60,4 @@ module.exports = {
         success(contacts);
     }
 
-};
\ No newline at end of file
+};

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/common/channel.js
----------------------------------------------------------------------
diff --git a/lib/common/channel.js b/lib/common/channel.js
index 8c33a42..329efda 100755
--- a/lib/common/channel.js
+++ b/lib/common/channel.js
@@ -1,3 +1,5 @@
+var utils = require('cordova/utils');
+
 /**
  * Custom pub-sub "channel" that can have functions subscribed to it
  * This object is used to define and control firing of events for
@@ -45,21 +47,21 @@
  *                       context to the Channel.
  */
 var Channel = function(type, opts) {
-        this.type = type;
-        this.handlers = {};
-        this.numHandlers = 0;
-        this.guid = 0;
-        this.fired = false;
-        this.enabled = true;
-        this.events = {
-          onSubscribe:null,
-          onUnsubscribe:null
-        };
-        if (opts) {
-          if (opts.onSubscribe) this.events.onSubscribe = opts.onSubscribe;
-          if (opts.onUnsubscribe) this.events.onUnsubscribe = opts.onUnsubscribe;
-        }
-    },
+    this.type = type;
+    this.handlers = {};
+    this.numHandlers = 0;
+    this.guid = 0;
+    this.fired = false;
+    this.enabled = true;
+    this.events = {
+        onSubscribe:null,
+        onUnsubscribe:null
+    };
+    if (opts) {
+        if (opts.onSubscribe) this.events.onSubscribe = opts.onSubscribe;
+        if (opts.onUnsubscribe) this.events.onUnsubscribe = opts.onUnsubscribe;
+    }
+},
     channel = {
         /**
          * Calls the provided function only after all of the channels specified
@@ -119,8 +121,11 @@ var Channel = function(type, opts) {
                 c.fire();
             }
         }
-    },
-    utils = require('cordova/utils');
+    };
+
+function forceFunction(f) {
+    if (f === null || f === undefined || typeof f != 'function') throw "Function required as first argument!";
+}
 
 /**
  * Subscribes the given function to the channel. Any time that
@@ -131,10 +136,10 @@ var Channel = function(type, opts) {
  */
 Channel.prototype.subscribe = function(f, c, g) {
     // need a function to call
-    if (f === null || f === undefined) { return; }
+    forceFunction(f);
 
     var func = f;
-    if (typeof c == "object" && f instanceof Function) { func = utils.close(c, f); }
+    if (typeof c == "object") { func = utils.close(c, f); }
 
     g = g || func.observer_guid || f.observer_guid || this.guid++;
     func.observer_guid = g;
@@ -151,7 +156,7 @@ Channel.prototype.subscribe = function(f, c, g) {
  */
 Channel.prototype.subscribeOnce = function(f, c) {
     // need a function to call
-    if (f === null || f === undefined) { return; }
+    forceFunction(f);
 
     var g = null;
     var _this = this;
@@ -160,7 +165,7 @@ Channel.prototype.subscribeOnce = function(f, c) {
         _this.unsubscribe(g);
     };
     if (this.fired) {
-        if (typeof c == "object" && f instanceof Function) { f = utils.close(c, f); }
+        if (typeof c == "object") { f = utils.close(c, f); }
         f.apply(this, this.fireArgs);
     } else {
         g = this.subscribe(m);
@@ -173,9 +178,9 @@ Channel.prototype.subscribeOnce = function(f, c) {
  */
 Channel.prototype.unsubscribe = function(g) {
     // need a function to unsubscribe
-    if (g === null || g === undefined) { return; }
+    if (g === null || g === undefined) { throw "You must pass _something_ into Channel.unsubscribe"; }
 
-    if (g instanceof Function) { g = g.observer_guid; }
+    if (typeof g == 'function') { g = g.observer_guid; }
     this.handlers[g] = null;
     delete this.handlers[g];
     this.numHandlers--;
@@ -191,7 +196,7 @@ Channel.prototype.fire = function(e) {
         this.fired = true;
         for (var item in this.handlers) {
             var handler = this.handlers[item];
-            if (handler instanceof Function) {
+            if (typeof handler == 'function') {
                 var rv = (handler.apply(this, arguments)===false);
                 fail = fail || rv;
             }
@@ -236,4 +241,4 @@ channel.waitForInitialization('onCordovaReady');
 channel.waitForInitialization('onCordovaInfoReady');
 channel.waitForInitialization('onCordovaConnectionReady');
 
-module.exports = channel;
\ No newline at end of file
+module.exports = channel;

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/common/plugin/Contact.js
----------------------------------------------------------------------
diff --git a/lib/common/plugin/Contact.js b/lib/common/plugin/Contact.js
index 1e8c9ce..6aa51d9 100644
--- a/lib/common/plugin/Contact.js
+++ b/lib/common/plugin/Contact.js
@@ -25,14 +25,14 @@ function convertOut(contact) {
     var value = contact.birthday;
     if (value !== null) {
         // try to make it a Date object if it is not already
-        if (!value instanceof Date){
+        if (!utils.isDate(value)){
             try {
                 value = new Date(value);
             } catch(exception){
                 value = null;
             }
         }
-        if (value instanceof Date){
+        if (utils.isDate(value)){
             value = value.valueOf(); // convert to milliseconds
         }
         contact.birthday = value;
@@ -174,4 +174,4 @@ Contact.prototype.save = function(successCB, errorCB) {
 };
 
 
-module.exports = Contact;
\ No newline at end of file
+module.exports = Contact;

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/common/plugin/FileTransfer.js
----------------------------------------------------------------------
diff --git a/lib/common/plugin/FileTransfer.js b/lib/common/plugin/FileTransfer.js
index 60024df..8742956 100644
--- a/lib/common/plugin/FileTransfer.js
+++ b/lib/common/plugin/FileTransfer.js
@@ -27,7 +27,7 @@ FileTransfer.prototype.upload = function(filePath, server, successCallback, erro
         fileKey = options.fileKey;
         fileName = options.fileName;
         mimeType = options.mimeType;
-        if (options.chunkedMode !== null || typeof options.chunkedMode !== "undefined") {
+        if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
             chunkedMode = options.chunkedMode;
         }
         if (options.params) {

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/common/plugin/contacts.js
----------------------------------------------------------------------
diff --git a/lib/common/plugin/contacts.js b/lib/common/plugin/contacts.js
index b958362..6737de5 100644
--- a/lib/common/plugin/contacts.js
+++ b/lib/common/plugin/contacts.js
@@ -1,5 +1,6 @@
 var exec = require('cordova/exec'),
     ContactError = require('cordova/plugin/ContactError'),
+    utils = require('cordova/utils'),
     Contact = require('cordova/plugin/Contact');
 
 /**
@@ -19,7 +20,7 @@ var contacts = {
         if (!successCB) {
             throw new TypeError("You must specify a success callback for the find command.");
         }
-        if (!fields || (fields instanceof Array && fields.length === 0)) {
+        if (!fields || (utils.isArray(fields) && fields.length === 0)) {
             if (typeof errorCB === "function") {
                 errorCB(new ContactError(ContactError.INVALID_ARGUMENT_ERROR));
             }
@@ -54,4 +55,4 @@ var contacts = {
     }
 };
 
-module.exports = contacts;
\ No newline at end of file
+module.exports = contacts;

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/common/utils.js
----------------------------------------------------------------------
diff --git a/lib/common/utils.js b/lib/common/utils.js
index fa2c534..b2ee8cb 100644
--- a/lib/common/utils.js
+++ b/lib/common/utils.js
@@ -11,17 +11,23 @@ function UUIDcreatePart(length) {
 }
 
 var _self = {
+    isArray:function(a) {
+        return Object.prototype.toString.call(a) == '[object Array]';
+    },
+    isDate:function(d) {
+        return Object.prototype.toString.call(d) == '[object Date]';
+    },
     /**
      * Does a deep clone of the object.
      */
     clone: function(obj) {
-        if(!obj) {
+        if(!obj || typeof obj == 'function' || _self.isDate(obj) || typeof obj != 'object') {
             return obj;
         }
 
         var retVal, i;
 
-        if(obj instanceof Array){
+        if(_self.isArray(obj)){
             retVal = [];
             for(i = 0; i < obj.length; ++i){
                 retVal.push(_self.clone(obj[i]));
@@ -29,18 +35,6 @@ var _self = {
             return retVal;
         }
 
-        if (obj instanceof Function) {
-            return obj;
-        }
-
-        if(!(obj instanceof Object)){
-            return obj;
-        }
-
-        if(obj instanceof Date){
-            return obj;
-        }
-
         retVal = {};
         for(i in obj){
             if(!(i in retVal) || retVal[i] != obj[i]) {
@@ -51,7 +45,7 @@ var _self = {
     },
 
     close: function(context, func, params) {
-        if (typeof params === 'undefined') {
+        if (typeof params == 'undefined') {
             return function() {
                 return func.apply(context, arguments);
             };
@@ -101,4 +95,4 @@ var _self = {
     }
 };
 
-module.exports = _self;
\ No newline at end of file
+module.exports = _self;

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/cordova.js
----------------------------------------------------------------------
diff --git a/lib/cordova.js b/lib/cordova.js
index f6a754d..d3da481 100644
--- a/lib/cordova.js
+++ b/lib/cordova.js
@@ -32,7 +32,7 @@ document.addEventListener = function(evt, handler, capture) {
     } else if (e == 'resume') {
         channel.onResume.subscribe(handler);
         // if subscribing listener after event has already fired, invoke the handler
-        if (channel.onResume.fired && handler instanceof Function) {
+        if (channel.onResume.fired && typeof handler == 'function') {
             handler();
         }
     } else if (e == 'pause') {

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/lib/ios/exec.js
----------------------------------------------------------------------
diff --git a/lib/ios/exec.js b/lib/ios/exec.js
index 0a3b796..8726cc6 100644
--- a/lib/ios/exec.js
+++ b/lib/ios/exec.js
@@ -69,7 +69,7 @@ module.exports = function() {
         var arg = actionArgs[i];
         if (arg === undefined || arg === null) { // nulls are pushed to the args now (becomes NSNull)
             command["arguments"].push(arg);
-        } else if (typeof(arg) == 'object' && !(arg instanceof Array)) {
+        } else if (typeof(arg) == 'object' && !(utils.isArray(arg))) {
             command.options = arg;
         } else {
             command["arguments"].push(arg);

http://git-wip-us.apache.org/repos/asf/incubator-cordova-js/blob/f9f51d94/test/test.channel.js
----------------------------------------------------------------------
diff --git a/test/test.channel.js b/test/test.channel.js
index b85997e..c8bb43d 100644
--- a/test/test.channel.js
+++ b/test/test.channel.js
@@ -2,15 +2,37 @@ describe("channel", function () {
     var channel = require('cordova/channel');
 
     describe("when subscribing", function() {
+        it("should throw an exception if no function is provided", function() {
+            var c = channel.create('test');
+            expect(function() {
+                c.subscribe();
+            }).toThrow();
+
+            expect(function() {
+                c.subscribe(null);
+            }).toThrow();
+
+            expect(function() {
+                c.subscribe(undefined);
+            }).toThrow();
+
+            expect(function() {
+                c.subscribe({apply:function(){},call:function(){}});
+            }).toThrow();
+        });
         it("should not change number of handlers if no function is provided", function() {
             var c = channel.create('heydawg');
             var initialLength = c.numHandlers;
 
-            c.subscribe();
+            try {
+                c.subscribe();
+            } catch(e) {}
 
             expect(c.numHandlers).toEqual(initialLength);
 
-            c.subscribe(null);
+            try {
+                c.subscribe(null);
+            } catch(e) {}
 
             expect(c.numHandlers).toEqual(initialLength);
         });