Skip to content

JavaScript Views

snej edited this page Jan 23, 2013 · 7 revisions

It is now (as of January 2013) possible to write map/reduce functions in JavaScript. This page explains how, after first trying to talk you out of it.

Pros:

  • Reuse existing map/reduce functions from a CouchDB app.
  • 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.

How To Do It

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

  1. Copy TDJSViewCompiler.h and TDJSViewCompiler.m from the Source folder of the TouchDB 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 TouchDB initialization code, add the line:
[TD_View setCompiler: [[TDJSViewCompiler alloc] init]];

You'll also need to add #import <TouchDB/TD_View.h> to the top of the source file.

That's it. TouchDB will now recognize JavaScript map/reduce functions stored in design documents just like CouchDB does.