Skip to content
Fix Code Error

Emberjs DefaultTo Computed Property

April 7, 2021 by Code Error
Posted By: Anonymous

Often, I want my views to default to a specific value if the actual model property is not set.
This placeholder text/value is strictly view only and hence, should not be placed in the model imo.

So, this is what I end up doing:

// Sample 'Model' for illustration purposes only.
var myModel = Ember.Object.extend({
  title: null,

  description: null,

  thumbUrl: null
});

/**
 * Sample View
 * Render view properties which are actually 
 * computed of the actual 'content' properties
 */
var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('<p>Title: {{view.title}}</p> <p>Description: {{view.description}}</p> <p>Image: <img {{bindAttr src="view.thumbUrl"}}/></p>'),

  title: function () {
    return this.get('content.title') || 'Title goes here';// placeholder 'title' text
  }.property('content.title'),

  description: function () {
    return this.get('content.description') || 'This is your description'; // placeholder 'description'
  }.property('content.description'),

  thumbUrl: function () {
    return this.get('content.thumbUrl') || 'http://placehold.it/100x100';
  }.property('content.thumbUrl')
});

Any suggestions on how can I reduce boilerplate on defining defaults on all those properties i.e. ‘title’, ‘description’ and ‘thumbUrl’ ?

I looked into Ember.computed.defaultTo but failed to understand on how I can use it. This is how I envision it in action:

var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('<p>Title: {{view.title}}</p> <p>Description: {{view.description}}</p> <p>Image: <img {{bindAttr src="view.thumbUrl"}}/></p>'),

  title: Ember.computed.defaultTo('content.title', 'Title goes here'),

  description: Ember.computed.defaultTo('content.description', 'This is your description'),

  thumbUrl: Ember.computed.defaultTo('content.thumbUrl', 'http://placehold.it/100x100')
});

So how can this be done ?

If there are better approaches to do this type of a thing, I would like to hear them in the comments.

Also, pointers to what Ember.computed.defaultTo does would be really helpful as well.

Solution

This is not what Ember.computed.defaultTo is intended to do. Ember.computed.defaultTo takes a single defaultPath parameter. From the docs:

computed property which acts like a standard getter and setter, but defaults to the value from defaultPath.

If you read the test, it sheds some light.

testBoth('Ember.computed.defaultTo', function(get, set) {
  var obj = { source: 'original source value' };
  Ember.defineProperty(obj, 'copy', Ember.computed.defaultTo('source'));

  equal(get(obj, 'copy'), 'original source value');

  set(obj, 'copy', 'new copy value');
  equal(get(obj, 'source'), 'original source value');
  equal(get(obj, 'copy'), 'new copy value');

  set(obj, 'source', 'new source value');
  equal(get(obj, 'copy'), 'new copy value');

  set(obj, 'copy', null);
  equal(get(obj, 'copy'), 'new source value');
});

Instead, you could write your own helper like so:

Ember.computed.defaultValue = function(dependentKey, defaultValue) {
  return Ember.computed(dependentKey, function() {
    return Ember.get(this, dependentKey) || defaultValue;
  });
};

var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('<p>Title: {{view.title}}</p> <p>Description: {{view.description}}</p> <p>Image: <img {{bindAttr src="view.thumbUrl"}}/></p>'),

  title: Ember.computed.defaultValue('content.title', 'Title goes here'),

  description: Ember.computed.defaultValue('content.description', 'This is your description'),

  thumbUrl: Ember.computed.defaultValue('content.thumbUrl', 'http://placehold.it/100x100')
});

If you’d rather not create your own helper function, an alternative approach would be to use separate properties for default values and then use Ember.computed.any.

var myView = Ember.View.extend({
  template: Ember.Handlebars.compile('<p>Title: {{view.title}}</p> <p>Description: {{view.description}}</p> <p>Image: <img {{bindAttr src="view.thumbUrl"}}/></p>'),

  defaultTitle: 'Title goes here',
  title: Ember.computed.any('content.title', 'defaultTitle'),

  defaultDescription: 'This is your description',
  description: Ember.computed.any('content.description', 'defaultDescription'),

  defaultThumbUrl: 'http://placehold.it/100x100',
  thumbUrl: Ember.computed.any('content.thumbUrl', 'defaultThumbUrl')
});
Answered By: Anonymous

Related Articles

  • How to represent arrays within ember-data models?
  • Is it possible to apply CSS to half of a character?
  • Maven2: Missing artifact but jars are in place
  • how to access parent component scope from a child…
  • Rendering ember component outside parent template
  • Right way to do navigation with Ember
  • GLYPHICONS - bootstrap icon font hex value
  • How to handle initializing and rendering subviews in…
  • Backbone.js - Should nested Views maintain…
  • Ember view template as a computed property
  • Ember.JS - How to use multiple models, controllers…
  • Easy way to precompile Emberjs Handlebar templates…
  • Binding a Backbone Model to a Marionette ItemView -…
  • Ember.js: "Undefined is not a function" in internal…
  • How to dynamically add and remove views with Ember.js
  • Testing backbone.js application with jasmine - how…
  • Ember.js - Using a Handlebars helper to detect that…
  • How to vertically align an image inside a div
  • attaching backbone.js views to existing elements vs.…
  • Ember.js - CRUD scenarios - Specifying View from…
  • Ember-table integration with Ember-model / Ember-data
  • In CSS Flexbox, why are there no "justify-items" and…
  • Creating layout constraints programmatically
  • Multiple outlets in Ember.js v2 router
  • Why does my Handlebars not have a compile method?
  • Break up my application.handlebars into separate…
  • Ember.js - doing it right (structure, includes,…
  • Nested routes rendering into same template/outlet…
  • get clean HTML from emberjs handlebars application
  • show/hide div/view with backbone.js
  • How does Ember.js reference Grunt.js precompiled…
  • coercing to Unicode: need string or buffer, NoneType…
  • Centering in CSS Grid
  • Polymer Dom-Repeat Binding to Content
  • How to use html template with vue.js
  • Using DS.model or Ember.model or Ember.Object when…
  • Appending Ember Component to a DOM element not…
  • What are the nuances of scope prototypal /…
  • Change a HTML5 input's placeholder color with CSS
  • Ember.js with external handlebars template
  • Using Auto Layout in UITableView for dynamic cell…
  • Handlebars If statement inside each loses context
  • error: resource android:attr/fontVariationSettings not found
  • How to Access XHR Object making backbone.model save
  • Ember CLI - Uncaught Error: Could not find module ember?
  • What is Ember RunLoop and how does it work?
  • Create a new model in View.event Backbone.js
  • Ember.js: How to refresh parent route templates in a…
  • Unknown template object error with handlebars 2.0 runtime
  • Uncaught Error: Could not find module `ember`…
  • How to communicate between controllers in Ember.js
  • It's difficult to learn ember.js
  • Typeerror: n is undefined in underscore.min.js
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Ember js: Render Nested Navigation Sidebar together…
  • What's the difference between eval, exec, and compile?
  • Ember.js -- How do I target outlets in…
  • error [email protected]: The engine "node" is…
  • Render a Marionette region after model has been fetched
  • HTML5 Canvas Resize (Downscale) Image High Quality?
  • Updating Backbone.js View becoming a mess
  • Add placeholder text inside UITextView in Swift?
  • Ukkonen's suffix tree algorithm in plain English
  • laravel vuejs/axios put request Formdata is empty
  • Views vs Components in Ember.js
  • How to make the overflow CSS property work with…
  • BackboneJs: Uncaught TypeError: undefined is not a function
  • Ember.js: HtmlBars and the Handlebars.compile command
  • Why do Model attributes get added to my…
  • BackboneJS: View renders fine, but refreshes with…
  • Conventions required of RESTful JSON API to be…
  • Difference between Ember.get() and this.get()
  • backbone.js view renders before model fetch
  • Bulma - why all columns are on one line?
  • EmberJS, polling, update route's model, re-render component
  • Ember.js value binding with HTML5 file upload
  • BackboneJS Rendering Problems
  • ember.js + handlebars: render vs outlet vs partial…
  • jquery: get value of custom attribute
  • Ember.js Controller & View Binding (The ember.js way...)
  • How to render template other than application.hbs in…
  • dynamically add and remove view to viewpager
  • How can I use/create dynamic template to compile…
  • Ember.js: How to call a method defined in model from view?
  • Combing conditional class binding with existing class
  • Emberjs bindAttr inside of #each
  • is handling custom server side errors in ember-data…
  • How to separate opening and closing tag by…
  • VueJS: Cannot read property 'name' of undefined"
  • How to pass a template to a view in Backbone
  • How to create and extend Ember.ArrayController in…
  • Polling request for updating Backbone Models/Views
  • How do I get and print an .hbs or .handlebars template?
  • ember hbs templates as separate files
  • Backbone: Multiple views subscribing to a single…
  • Set controller for template rendering
  • Vue.js 2 router only loading component from…
  • Backbone Collection.fetch gives me Uncaught…
  • Backbone render return this
  • Capture div containing inline svg and download it as image

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Backbone parse ajax response function not being called

Next Post:

Vue unit tests failing because component method calls this.$route.query – TypeError: Cannot read property ‘query’ of undefined

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Vue 3 Composition API Provide/Inject not working in Single File Components
  • Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead
  • How to pass a model to a template rendered from a route in Ember 1.6
  • Backbonejs – Avoid parse after save
  • BackboneJS: View renders fine, but refreshes with undefined collection
  • Explicit call vuex actions in the `.vue` component detach/ready function
  • jest.fn() claims not to have been called, but has
  • I18Next doesn’t work when loading data from backend
  • Properly setting the context for an Ember partial rendered from within a template
  • Custom Backbone Sync
  • Vue-router page refresh or URL access
  • Vue.js – Unknown custom element:
  • server returning 302 moved on create in Rails
  • TypeError: Cannot call method ‘replace’ of null – Backbone.js
  • Capture div containing inline svg and download it as image
  • Overview of the Ember.js code
  • Polymer 1.0 – HIDE Paper Drawer Panel
  • How to get a backend error message on the frontend using Fetch
  • How to change day-format (M > Mo, F > Fr…) in Date/month pickers of Vuetify
  • Vue.js cache method outcome?

Categories Tags

.net (1074) ajax (457) android (2318) angularjs (553) arrays (1090) asp.net (630) backbone.js (2262) bash (760) c++ (4925) css (2466) date (485) datetime (471) ember.js (1279) excel (566) git (1084) html (3345) ios (701) java (4508) javascript (9390) jquery (2998) json (943) laravel (507) linux (797) list (561) mysql (1310) node.js (895) oracle (475) pandas (449) php (2230) python (4372) r (537) reactjs (545) regex (554) shell (517) sql (1847) sql-server (1217) string (1360) tsql (471) twitter-bootstrap (515) typescript (418) vue-component (716) vue.js (5164) vuejs2 (1675) vuetify.js (495) windows (590)
© 2021 Fix Code Error