Search code examples
model-view-controllerbackbone.jsattributesmodels

Updating Backbone Model Attributes Dynamically


I have a model that is part of a collection and retrieves data from the api. This model contains (among other attributes) the following attributes:

updatedDate //-> value retreived from API/DB
lastUpdateAttempt //-> value retrieved from API/DB
status //-> value NOT retrieved from API/DB, depends on values of above two attributes ("updated", "error", "out of date", etc...).

My question is, how can/when should I set the status attribute? Is there a way where I can dynamically set status when trying to retrieve the value? (i.e. modelObj.get("status") -> calls function to calculate value, returns result). Or should I call a function from the view to update this attribute on initialize, then add an event listener that does the same on change? (<-- somehow doesn't seem like the best solution)

I have a feeling I'm overthinking this and there is a really practical way of doing this, but I'm still a bit inexperienced with Backbone.

Thanks.


Solution

  • You can set the initial value of status, and listen for further changes to updatedDate or lastUpdateAttempt when the model is initialized.

    Something like

    Backbone.Model.extend({
      initialize: function(){
         this.updateStatus();
         this.on("change:updatedDate change:lastUpdateAttempt",this.updateStatus);
      },
      updateStatus: function(){
       // your logic
      }
    });
    

    Or you can try this weird way (not at all tested, just a thought), which is somewhat like updating the status while accessing it. Might help if you want to control the frequency of status updates. (if you are likely to access the status way less than the number of changes that is likely to occur with the other two properties)

    Backbone.Model.extend({
      initialize: function(){
         this.updateStatus();
         this.on("updateStatus",this.updateStatus);
      },
      updateStatus: function(){
       // your logic
      }
    });
    

    and access the status like, model.trigger('updateStatus').get('status')