0

I'm pretty new to BackboneJS, looking for some help in the defaulting an attribute based on a condition How can I default name to TEST based on a condition that is only if model.attribute = 'xyz' in Backbone models.

defaults: function() {
  return {
   name: 'TEST'
  }
}

Thanks

1 Answer 1

2

You set defaults when you extend a Backbone model so you don't really have access to any instance attributes there.

If the default values you want to change depend on instance modal attributes set on instatiation (i.e new MyModel({foo:"bar"})) when you'd be better of setting an initialize() callback when extending your model.

var MyModel = Backbone.Model.extend({
  initialize: function(options) {
    // I have access to this.attributes here
  }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Notice that defaults is a function in the question. So your first sentence is wrong. this.attributes is empty when accessed in the defaults function because attributes are in the process of being set, hence the defaults function being called.
That makes sense, Thanks all for your help.
@EmileBergeron I think there's nothing wrong with what I've said. Instance attributes haven't been populated at the time the defaults is evaled through Underscore's result()
"when you extend a Backbone model", written as if the code runs only when extending the model class, which is false since it's a function that is called each time a model is instantiated. You do have access to the instance attributes hash, but it is empty at that point. What you don't have access to is the passed attributes (new MyModel({foo:"bar"})) because the defaults function receives no parameters.
I did upvote you though, that is just nitpicking on my part ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.