/var/log

Titanium, Backbone and Promises

An easy way to let Backbone work with Promises in Titanium:

Get the bluebird Promise library.

Now you can add a fetchAsPromise to the Backbone.Model.Prototype and Backbone.Collection.prototype objects:

Backbone.Model.prototype.fetchAsPromise = function(options) {
  var me = this;
  return new Promise(function(resolve, reject) {
    options.success = resolve;
    options.error = reject;
    me.fetch(options);
  });
};

The same can be done for the save method:

Backbone.Model.prototype.saveAsPromise = function(props) {
  var me = this;
  return new Promise(function(resolve, reject) {
    me.save(props, {
      success : resolve,
      error : reject
    });
  });
};

Now you can do:

var user;

Alloy.createModel("User").fetchAsPromise({
  id : 12
}).then(function(bbUser) {
  user = bbUser;
  return Alloy.createCollection("Orders").fetchAsPromise({
    query : "select * from Orders where user_id = " + user.get("id")
  });
}).then(function(orders) {
  // Now we have user and orders...
});
Tag: , | Category: