javascriptprototypecanjscanjs-control

Can.js - Adding a can.Compute to prototype


How might I add a can.compute to a can.Control instance prototype? I'm trying to pass it into the instance functions with extend, but all instances of the class share the same single instance of the compute.

can.Control.extend('App.Window', {
  ...
},{
  ...
  active: can.compute(true, function(newVal, oldVal) {
    return !!newVal;
  })
});

var a = new App.Window,
    b = new App.Window;

a.active === b.active // true
a.active()           // true
a.active(false)
a.active()         // false
b.active()        // false

Obviously I could just do this in the init function, but I'd rather not, so as I inherit from this in the future, I won't have to remember to call the parent init. Just hoping someone has a better way.


Solution

  • Sharing the same instance is kind of the point of the prototype. You could use a prototype function that returns the new compute. An alternative to using the Controls init would be to use the prototype setup or modifying the options in the static setup:

    can.Control.extend('App.Window', {
      ...
    },{
      setup: function(element, options) {
            this.active = can.compute(true, function(newVal, oldVal) {
                return !!newVal;
            });
            return can.Control.prototype.setup.apply(this, arguments);
        }
    });