2017-07-07 171 views

回答

0

您正在尋找的是訂閱。這些將監視指定的observable,並在observable發生更改時運行。他們將新價值傳遞給您指定的任何功能。這是一個簡短的,儘管沒用的例子。

function viewModel() { 
 
    var self = this; 
 

 
    self.DisplayPage = ko.observable(""); 
 

 
    self.PageDetails = ko.observable(""); 
 

 
    self.DisplayPage.subscribe(function(newValue) { 
 
    if (newValue == "Home") { 
 
     self.PageDetails("No Place like home"); 
 
    } 
 
    if (newValue == "About") { 
 
     self.PageDetails("What about it?"); 
 
    } 
 
    if (newValue == "Contact") { 
 
     self.PageDetails("Contact who?"); 
 
    } 
 

 
    }) 
 

 
} 
 

 
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 
<select data-bind="value: DisplayPage"> 
 
    <option value="Home">Home</option> 
 
    <option value="About">About</option> 
 
    <option value="Contact">Contact</option> 
 
</select> 
 

 
<div> 
 

 
    <input data-bind="value: DisplayPage"> 
 

 
    <div data-bind="text: PageDetails"></div> 
 

 
</div>