Knockout是在下面三个核心功能是建立起来的:
-
监控属性(Observables)和依赖跟踪(Dependency tracking)
-
声明式绑定(Declarative bindings)
-
模板(Templating)
工作中,最重要的是建模,模型建好了,能减少很多的工作和代码,只要着重于维护好自己的模板。
用好它的依赖关系可以使连动很省事,不用操作dom元素,全部都是dom bind ,使页面和数据相分离,结构更清晰,更易于维护
简单例子:
html:<p>First name: <input data-bind="value: firstName"/></p><p>Last name: <input data-bind="value: lastName"/></p><h2>Hello, <span data-bind="text: fullName"> </span>!</h2>javascript:
var viewModel = { firstName: ko.observable("Planet"), lastName: ko.observable("Earth")}; viewModel.fullName = ko.dependentObservable(function () { // Knockout tracks dependencies automatically. //It knows that fullName depends on firstName and lastName, //because these get called when evaluating fullName. return viewModel.firstName() + " " + viewModel.lastName();}); ko.applyBindings(viewModel); // This makes Knockout get to work eg2:foreach循环输出<table> <thead> <tr> <td>Name</td> <td>Amount</td> <td>Price</td> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td data-bind="text: product.name"></td> <td><select data-bind="options:[1,2,3,4,5,6],value: amount"></select></td> <td data-bind="text: subTotal"></td> </tr> </tbody> </table>
当我改变模型里边的 firstname时,不仅模型里边的值改变了,页面上相应的值也会变。现在项目中用到的:1.ko的依赖属性2.表单验证3.模板等等也可以添加自定义的绑定。
时间: 2024-11-06 11:30:19