Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New feature: Model.get fallback callback/value. #1184

Closed
wants to merge 1 commit into from
Closed

New feature: Model.get fallback callback/value. #1184

wants to merge 1 commit into from

Conversation

frankdejonge
Copy link

When retrieving a value from a model this would be a nice structure to have a fallback, allowing:

var User = new UserModel;

var name = User.get('name', function(){
    // Not set? Use email
    return this.get('email');
});

Or just pass the default value on the fly

var name = User.get('name', 'Unkown');

Hope you like it.

@jashkenas
Copy link
Owner

That's what defaults already do. Take a look at those:

http://backbonejs.org/#Model-defaults

@jashkenas jashkenas closed this Apr 4, 2012
@frankdejonge
Copy link
Author

Actually, it's not what defaults do. Defaults are just plain values, no callbacks in context of the model, and not on the fly.

@braddunbar
Copy link
Collaborator

@FrenkyNet You're right about on the fly, but you can definitely implement them with a callback in context of the model.

var Model = Backbone.Model.extend({
  defaults: function() {
    return {
      ...
    };
  }
});

Also, model.get('key', 'default') is functionally equivalent to model.get('key') || 'default', and with no extra characters.

@frankdejonge
Copy link
Author

@braddunbar That || way should do the trick as well, but I'll still probably implement this in a model of my own. Thanks for the help!

@gsdevme
Copy link

gsdevme commented Sep 7, 2012

Using Pipe in templates isn't ideal.. Nor is using defaults when you might want different values based on the use case.

Surely justifying not using this by saying use pipe would argue the case to remove the has() method? After all you can just pipe? That is unless it's use case is uncommon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants