DoneJS StealJS jQuery ++ FuncUnit DocumentJS
3.0.0
2.3.27

 

  • Github
  • Twitter
  • Chat
  • Forum
  • Guides
  • Core
    • can-component
    • can-compute
      • computeSettings
      • compute
        • methods
          • addEventListener
          • off
          • on
          • removeEventListener
        • events
          • change
    • can-connect
    • can-define
    • can-define/list/list
    • can-define/map/map
    • can-route
    • can-route-pushstate
    • can-set
    • can-stache
    • can-stache/helpers/route
    • can-stache-bindings
  • Ecosystem
  • Infrastructure
  • Legacy
  • Bitovi
    • Bitovi.com
    • Blog
    • Consulting
    • Training
    • Open Source
  • Chat
  • Forum
  • Star
  • Follow @canjs
  • CanJS
  • /
  • Core
  • /
  • can-compute
  • /
  • compute
  • / On this page
    • compute

      function

      A derived value from other computes and observable maps.

      • source

      compute([newVal])

      Gets the compute's value if no arguments are provided, otherwise calls the compute's setter with the value passed as the first argument.

      Parameters

      1. newVal {*}:

        If the compute is called with an argument, the first argument is used to set the compute to a new value. This may trigger a "change" event that can be listened for with [can-computed.bind].

        If the compute is called without any arguments (compute()), it simply returns the current value.

      Returns

      {*}:

      The current value of the compute.

      Use

      A compute instance is created with can-compute and used as an observable value. Computes are useful to provide a value representative of multiple other observables:

      var person = new Person({
          first: "Matthew",
          last: "Phillips"
      });
      
      var fullName = compute(function(){
          return person.first + " " + person.last;
      });
      
      console.log(fullName()); // -> "Matthew Phillips".
      

      Calling the compute with a value will cause it to run as a setter function:

      var count = compute(0);
      
      console.log(count()); // -> 0
      
      count(5);
      
      console.log(count()); // -> 5
      

      This depends on how the getterSetter is defined, and can adjust how it handles setters:

      var plusOne = compute(function(val){
          if(val) {
              return val + 1;
          } else {
              return 1;
          }
      });
      
      console.log(plusOne()); // -> 1
      
      plusOne(5);
      
      console.log(plusOne()); // -> 6
      

      CanJS is part of DoneJS. Created and maintained by the core DoneJS team and Bitovi. Currently 3.0.0.