Search code examples
javascriptjquerybackbone.jsbackbone-model

check for model attribute before fetch


I have this line of code in my method in a backbone router.

$.when(system.sideEngine.fetch(), system.lifeSupport.fetch()).done( ...

It works fine if the system has a sideEngineId and a lifeSupportId. However if either id is missing, I get a 404 not found error, and my page won't load.

I tried including an error statement like this:

error: function (model, xhr, options) {
    console.log("something went wrong!");
}

But that's not what I'm looking for. I don't want the absence of ids to be a show stopper. I still want the system to load regardless.

Is there a way to conditionally check for an id before I do a fetch other than creating a complicated if/then tree?


Solution

  • The isNew function should help in this case.

    If the model does not yet have an id, it is considered to be new.

    var MyModel = Backbone.Model.extend({
      idAttribute: 'whatever',
    
      fetch: function() {
        $('#result').append('fetch fired!<br/>');
        return null;
      }
    });
    
    var noId = new MyModel(),
      hasId = new MyModel({
        whatever: 5
      });
    
    $.when(
      noId.isNew() ? null : noId.fetch(),
      hasId.isNew() ? null : hasId.fetch()
    ).done(function() {
      $('#result').append('done fired!');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
    <div id="result" />

    $.when(
        system.sideEngine.isNew() ? null : system.sideEngine.fetch(), 
        system.lifeSupport.isNew() ? null : system.lifeSupport.fetch()
    ).done(function() {
        ...
    });
    

    Note that the null acts like a noop in this case.

    If you plan to use this regularly, might be worth considering:

    Backbone.Model.prototype.fetchIfId = function() {
        return this.isNew() ? null : this.fetch();
    }