1、使用dependentObservable监控依赖属性
①使用dependentObservable定义一个方法,方法中是需要依赖的属性
myViewModel.show_all = ko.dependentObservable(function () {
return myViewModel.string_label() + ‘~~~~‘ + myViewModel.string_p() + myViewModel.string_input();
})
②完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="knockout/knockout-3.5.1.js"></script> <!-- <script src="https://knockoutjs.com/downloads/knockout-3.5.1.js"></script> --> </head> <body> <h3 class="text-center text-success">debug page</h3> <label data-bind="text:string_label"></label> <p data-bind="text:string_p"></p> <input type="text" data-bind="value:string_input"> <p><b>注意:</b>input标签的文本需要使用textinput,其他标签用text即可</p> <p>---------------------------------------------------------------------------------------</p> <p>监控依赖使用</p> <p data-bind="text:show_all"></p> </body> <script> var myViewModel = { ‘string_label‘: ko.observable(‘给label标签赋值文本‘), ‘string_p‘: ko.observable(‘给p标签赋值文本‘), ‘string_input‘: ko.observable(‘给input标签赋值文本‘), }; myViewModel.show_all = ko.dependentObservable(function () { return myViewModel.string_label() + ‘~~~~‘ + myViewModel.string_p() + myViewModel.string_input(); }) ko.applyBindings(myViewModel); </script> </html>
③运行截图