Skip to content

JavaScript Views

Chris Anderson edited this page Jul 30, 2013 · 7 revisions

It is now possible to write map/reduce functions in JavaScript. This page explains how … after first trying to talk you out of it.

Pros:

  • You can reuse them between iOS and Android versions of a mobile app.
  • Syntax is slightly simpler than Objective-C.
  • The functions can be stored in a 'canned' database packaged with the app, and can be updated without having to recompile the app's main code.
  • The functions can be stored in a design document in a server-side database and replicated down to clients (but see the corresponding 'Con' point below!)

Cons:

  • Significantly slower to run, and use more memory, than native functions.
  • On iOS you'll have to link in a custom copy of the JavaScriptCore framework, which will add significant code size to your app.
  • On iOS, replicating a map/reduce function from a server is a violation of Apple's App Store Review Guidelines, section 2.7: "Apps that download code in any way or form will be rejected", and Apple can reject your app or pull it from the App Store at any time. It is legal to store canned JS functions in your app package and run them, since they're installed along with the app and not downloaded by it.

How To Do It

The functionality is available as a plug-in CBLViewCompiler that you register with Couchbase Lite at launch time. Once registered, it will take care of compiling functions from design documents, converting them into native CBLMapBlock or CBLReduceBlock blocks that call the function via JavaScriptCore.

  1. Copy CBLJSViewCompiler.h and CBLJSViewCompiler.m from the Source folder of the Couchbase Lite repository into your project's source tree.
  2. Add these files to your Xcode project.
  3. On Mac OS, make your target link against the built-in JavaScriptCore.framework. On iOS, download a copy of JavaScriptCore-iOS and add the library to your project.
  4. In your app's Couchbase Lite initialization code, add the line:
[CBLView setCompiler: [[CBLJSViewCompiler alloc] init]];

That's it. Couchbase Lite will now recognize JavaScript map/reduce functions stored in design documents.

Clone this wiki locally