Most useful techniques for two way data binding with js

后端 未结 3 1302
面向向阳花
面向向阳花 2021-02-10 07:34

With abundance of web services and client side templating features of jQuery and likes, creating mashups or sites consuming a multitude of web services and posting data back to

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-10 08:29

    Angular is the most impressive player I've seen for two-way databinding. You can use plain old JavaScript objects, attach them to an Angular scope object, and then bind the scope to a section of the DOM. Here's an example for Angular 0.9. (Angular 1.0 uses a very different API to achieve the same thing.)

    // angular.compile() returns a databinding function
    var databind = angular.compile(document.documentElement);
    var model = angular.scope();
    
    // add data to the scope object
    model.greeting = "Hello, World!";
    model.colors = ["red", "green", "blue"];
    
    // hook 'em up
    databind(model);
    

    You can use angular expressions in the HTML for databinding, including form controls.

    
    
    
      {{color}}
    
    

    In this case, the greeting property of the scope objects gets updated with every keystroke in the textbox.

    Or if you don't want to use databinding expressions in your HTML, you can do everything manually.

    model.$watch("greeting", function (value) {
      // when the greeting changes, update the DOM
      $("input[name=greeting]").val(value);
    });
    

    Then every time you update the scope object and call $eval(), if anything has changed, listeners will be notified.

    model.greeting = "Hi.";
    model.$eval();
    

    And the best part is that you can make changes to anything attached to the scope, call its $eval() method, and the HTML automatically updates.

    model.colors.append("yellow");
    model.colors.sort();
    model.$eval(); // notifies listeners, including bound HTML
    

    Knockout JS is inferior because instead of working with plain JavaScript objects, arrays, strings, and numbers, you must create instances of its Observable and ObservableArray classes to do databinding.

    Enjoy!

提交回复
热议问题