Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Re : Re: Data-Driven Javascript Controls -- What about checking checkboxes?

$
0
0
Yea,  your approach is awfully overcomplicated. Here:

  1. can.Component.extend({
  2.   tag: 'checkbox-list',
  3.   scope: {
  4.     list: [],
  5.     checkAll: function() {
  6.       this.attr('list').forEach(function( item, index, list ) {
  7.         item.attr('checked', true);
  8.       });
  9.     },
  10.     numberSelected: function() {
  11.       var count = 0;
  12.       this.attr('list').forEach(function( item, index, list ) {
  13.         if(item.attr('checked')) {
  14.           count++;
  15.         }
  16.       }
  17.     },
  18.     allSelected: function() {
  19.       return this.attr('numberSelected') === this.attr('list.length');
  20.     },
  21.     noneSelected: function() {
  22.       return this.attr('numberSelected') === this.attr('list.length');
  23.     }
  24.   }
  25. });


Within your view, you can utilize can-value="checked" to cross bind each items scope attributes with it's value. From there, you only need to interact with the scope, and don't need to do any DOM interaction, and you can compute the rest.

If you want to continue redefining what the checked attribute correlates too, you can simply modify where those values are being looked up in checkAll, and numberSelected. Within your view, you can use the attribute directly, ie: can-value="checked" instead of can-value="{{checkboxFieldValue}}", as you're overriding that anyway to match your passed scope. You can also skip initializing value, and skip the if checks for defining properties: id="{{id}}" is sufficient and preferred. 


Viewing all articles
Browse latest Browse all 3491

Trending Articles