coresmart / persistencejs

persistence.js is an asynchronous Javascript database mapper library. You can use it in the browser, as well on the server (and you can share data models between them).
http://persistencejs.org
1.73k stars 240 forks source link

Make available as AMD-style module for use with browserify / require.js #158

Open mobidev111 opened 9 years ago

mobidev111 commented 9 years ago

The persistence.js library is not available as AMD compatible module.

Use case: use the websql adapter within a client-side cordova app with angular and browserify package manager.

For example, persistence.js requires a dirty hack to use it with browserify:

// dirty persistence hack
var persistence = require('persistencejs');
var persistenceStoreSql = require('persistencejs/lib/persistence.store.sql');
persistence.store = {
  sql: {
    defaultTypeMapper: persistenceStoreSql.defaultTypeMapper,
    config: persistenceStoreSql.config
  }
};
var persistenceStoreWebsql = require('persistencejs/lib/persistence.store.websql');
persistence.store.websql = persistenceStoreWebsql.persistence.store.websql;
window.persistence = persistence;

An AMD-compatible wrapper solves this - see the following code showing the principle:

(function(name, definition) {
  if (typeof define === 'function') { // AMD
    define(definition);
  } else if (typeof module !== 'undefined' && module.exports) { // Node.js
    module.exports = definition();
  } else { // Browser
    var theModule = definition(),
      global = this,
      old = global[name];
    theModule.noConflict = function() {
      global[name] = old;
      return theModule;
    };
    global[name] = theModule;
  }
})('persistence', function() {
...
}
goldo commented 9 years ago

Thanks for the work-around of your 1st code. I needed it since i'm using webpack.

I think I noticed a small mistake tho, on first line ?
var persistence = require('persistencejs/lib/persistence').persistence; instead of var persistence = require('persistencejs');