2 way data binding in JavaScript

后端 未结 5 2200
栀梦
栀梦 2020-12-18 09:11

Two-way data binding refers to the ability to bind changes to an object’s properties to changes in the UI, and vice-versa.

Can we achieve 2-way data-binding with Jav

5条回答
  •  臣服心动
    2020-12-18 09:54

    Would you mind if it would be a small component for databinding tasks that provides enough convenient databinding definition commands. I did it with databindjs. e.g.

    // Lets assume that there is just simple form (target)
    var simpleForm = {
       input: $('.simple .input-value'),
       output: $('.simple .output-value')
    };
    // And here is the simple model object (source)
    var model = {
        text: 'initial value'
    };
    
    // Lets set two directional binding between [input] <-> [text]
    var simpleBinding = bindTo(simpleForm, () => model, {
        'input.val': 'text',  // bind to user input
        'output.text': 'text'  // simple region that will react on user input
    });
    // This command will sync values from source to target (from model to view)
    updateLayout(simpleBinding);
    subscribeToChange(simpleBinding, () => {
        $('.simple .console').html(JSON.stringify(model));
    });
    // Just initialize console from default model state
    $('.simple .console').html(JSON.stringify(model));
    

    The full solution here. You can check the full implementation of the databinding core on github

提交回复
热议问题