1

I am developing apps using Titanium and trying to implement the CommonJS approach. I like the modular setup, but I am wondering how best to deal with things like a shopping cart: temporary, user-created data that needs to last through the lifetime of the app.

I can see three approaches: 1. Create a special module for such a Cart. It will be created the first time it's require()d, and you can access the cart in its current state from any other module by require()ing it from those modules.

  1. Pass a quasi global Cart object to every module that needs it. This is in breach of the letter and the spirit of CommonJS.

  2. Store the Cart in local memory using Ti.App.Properties. This way, the cart is retained even when the user quits the app.

Any thoughts on what would be best?

4

1 回答 1

1

我更喜欢的解决方案是通过以下方式创建一个 CommonJS 模块:

function ShoppingCart(options) {
    // do some setup for the shopping cart
}

ShoppingCart.prototype.add(product, qty)
    // add product to cart
}

ShoppingCart.prototype.remove(product, qty)
    // remove product from cart
}

ShoppingCart.prototype.clear()
    // empty cart (and create new, empty one)
}

// etc.

ShoppingCart = new ShoppingCart();

module.exports = ShoppingCart;

如何访问?

var Cart = require('path/to/ShoppingCart');
Cart.add();
Cart.remove();
Cart.clear();

这会创建一种单例,它会在您第一次调用它时创建,并一直保存到应用程序完成(从内存中删除)或者您实现 clear 方法并自行清理它。你也可以使用这个单例来持久化数据,这取决于你要实现哪些部分。这与您的第一个想法相似。

您的第二个想法有几个缺点,因为数据访问未封装到模块中并且数据始终保持不变,因此您需要检测它是否旧并且可以删除。

最后,这取决于您的任务。您是否需要持久存储,您应该将模块与数据库结合起来。您是否仅在运行时需要此信息,模块就足够了。

于 2013-02-18T16:10:01.920 回答