canjs / can-observable-mixin

Define properties on JavaScript classes
https://canjs.com
MIT License
2 stars 1 forks source link

Proposal: make it possible to create behaviors using functions #122

Open phillipskevin opened 5 years ago

phillipskevin commented 5 years ago

I think it would be useful to make it possible to handle all of the different behaviors using functions.

To do this, we would need to create a standard format for what these return. Creating the behavior functions would be handled by another package.

For example, here is what an async and a value might look like:

import { ObservableObject, asyncGet, resolver } from "can/everything";

class AppViewModel extends ObservableObject {
  static define = {
    customerId: Number,
    // this uses an `asyncGet` function that creates a DefinitionObject type that has
    // specific Symbols that ObservableObject understands
    customer: asyncGet((resolve) => {
        Customer.get({ id: this.customerId })
          .then((customer) => {
            resolve(customer);
          });
    }),

    name: String,
    // this uses a `resolver` function that creates a DefinitionObject type that has
    // specific Symbols that ObservableObject understands
    nameChangeCount: resolver(({ listenTo, resolve }) => {
        let count = 0;
        listenTo( "name", () => resolve( ++count ) );
        resolve( count );
    })
  };
}

The benefits of this are:

The downsides are:

Related to https://github.com/canjs/can-stache-element/issues/47#issuecomment-509819918.