sproutcoresproutcore-viewssproutcore-controllers

sproutcore set color of a labelview dynamically depending on currentdate


I am rewriting a custom view to regular views. For example

Pseudo code
if (date = today) {
    context.push('...; style="color:red; ...}
else {
    context.push('...; style="color:black; ...}
;

becomes

mondayLabelView: SC.LabelView.extend({
        layout: {top:90, left:700, width:200, height:18},
        classNames: ['App-monday'],
        valueBinding: SC.Binding.oneWay('App.someController.selectedMondayDate'),
        }),

Question, how to rewrite the dynamic color part?


Solution

  • I would suggest using the classNameBindings property to dynamically add a CSS class. This way, you do not need to use the style tag.

    You can view more about it at http://blog.sproutcore.com/classnamebindings-easy-dynamic-css/ but the basic idea is as follows:

    mondayLabelView: SC.LabelView.extend({
       layout: {...},
       valueBinding: SC.Binding.oneWay('App.someController.selectedMondayDate'),
       isToday: function() {
         // Psuedo-code, you'll probably need SC.DateTime to actually compare the dates
         return this.get('value') == today;
       }.property('value'),
       classNameBindings: ['isToday:date-is-today'],
    })
    

    Then, in your CSS, you would have something like:

    .date-is-today {
      color: red;
    }