halfnelson / svelte-native

Svelte controlling native components via Nativescript
MIT License
1.82k stars 78 forks source link

[Proposal] Element bind:value mappings #348

Closed CatchABus closed 1 year ago

CatchABus commented 1 year ago

Right now, svelte-native uses svelte-native-preprocessor to allow the use of bind: directive for any attribute. That is because svelte is strict about which attributes support two-way binding. See #249

There are few drawbacks regarding this:

My proposal is to:

Here's how I visualize it:

export default class LabelElement extends NativeViewElementNode<Label> {
+  // All elements will have this property for their own supported property name
+  protected valueAttributeName: "text";

    constructor() {
        super("Label", Label);
    }

    static register() {
        registerElement("Label", () => new LabelElement());
    }
}

export default class NativeViewElementNode<T extends ViewBase> extends NativeElementNode<T> {
    setStyle(property: string, value: string | number) {
        log.debug(() => `setStyle ${this} ${property} ${value}`)

        if (!(value = value.toString().trim()).length) {
            return
        }

+      // This should make using value bind:value possible
+      if (property === this.valueAttributeName) {
+          property = 'value';
+      }

        if (property.endsWith('Align')) {
            // NativeScript uses Alignment instead of Align, this ensures that text-align works
            property += 'ment'
        }
        (this.nativeView.style as any)[property] = value
    }
}

So, one should be able to perform two-way binding using value:

<textfield bind:value={username}/>

Then, it's up to {N} users to get used to value attribute but compiler will complain about invalid two-way bindings either way. @halfnelson @farfromrefug What do you think about this?

CatchABus commented 1 year ago

Actually, even value demands that it's used with an input element but I'd really like to see a better solution for preprocessing.

CatchABus commented 1 year ago

Actually, even value demands that it's used with an input element but I'd really like to see a better solution for preprocessing.

After studying and searching for alternate ways to support bind, I close issue as namespace foreign doesn't give us much of a choice.