Search code examples
dojo2

Dojo 2 How to achieve two-way binding for input?


How to achieve 2 way data binding for input in dojo 2?

handleChange = (e) => {
  this.setState({ textValue: e.target.value });}
<Input name='title' defaultValue={this.state.textValue} placeholder='title...' onChange={this.handleChange} />

I know this is how we do in React but don't know how to achieve in dojo 2.


Solution

  • This is the solution to achieve 2 way data binding in Dojo 2.

    InputWidget:-

    interface IInputProps {
       value: string;
       onChange(event: Event): void;
    }
    export class InputWidget extends WidgetBase<IInputProps> {
      private _onChange (event: Event) {
        event.stopPropagation();
        this.properties.onChange && this.properties.onChange((event.target as HTMLInputElement).value);
      }
    
      protected render(): DNode {
        const { value } = this.properties;
        return v('input', { 
            key: "input",
            type: "text",
            value
            onchange: this._onChange
        });
      }
    }
    

    InputWrapper widget:-

    export class InputWrapper extends WidgetBase<IWrapperProps> {
      private inputValue: string = ''; 
      protected inputValueChanges(value: string) {
        this.inputValue = value;
        this.invalidate();
      }
    
      protected render(): DNode {
        <div>
            {w(InputWidget, {onchange: this.inputValueChanges, value: this.inputValue })}
            <span>Input Value:- {this.inputValue}</span>
        </div>
    
      }
    }
    

    This is the solution to achieve 2 way data binding in Dojo 2.

    Hope this will be helpful! :(