Beam-relational find or load?

Model caching inside Backbone-Relational is very good, but quite a lot of code is required to safely load a simple model. For example.

// Try and find a model in the Cache
this.model = MyModel.find({id:id});

if(this.model){
    // Model loaded from cache, do something.
    this.doSomething();
}else{
    // Load model then do something on success.

    var self =  this;

    this.model = new MyModel({id:id});
    this.model.fetch({
        success: function(){
            self.doSomething();
        }
    });
}

I think you could write a utility function, but it seems like the best way to do this? It seems too long.

+4
source share
2 answers

This is similar to the typical mysql / db operation.

You might want to structure this differently:

this.model = MyModel.find({id:id});

try {
    this.doSomething();
} catch (e) {
    if (e instanceof SomeSpecificException) {
        var fetchPromise = this.model.fetch();
        fetchPromise.done(
            this.doSomething.bind(this)
        );
    }
}

What's going on here?

Try/Catch - , - . , . Fetch / ( , ). (), doSomething, . .

?

- :

var Deferred = require('simply-deferred');

Backbone.Model.prototype.fetch = function(options) {
   var dfd = Deferred();

   Backbone.Model.prototype.fetch.call(
       this, 
       _.extend({ success: dfd.resolve.bind(this) }, options)
   );

   return dfd.promise;
}

, , - : Backbone.Model.prototype.fetch Backbone. , , , Backbone-Relational fetch ​​. , .

? , - node , promises , .

0

, , , , . .

this.model = MyModel.findOrCreate({id:id}).fetch({
    success: function(){
        self.doSomething();
    }
});
0

All Articles