转载

knockoutJS-Forcing observables to always notify subscribers

When writing to an observable that contains a primitive value (a

number, string, boolean, or null), the dependencies of the observable

are normally only notified if the value actually changed. However, it

is possible to use the built-in notify extender to ensure that an

observable’s subscribers are always notified on a write, even if the

value is the same. You would apply the extender to an observable like

this:

翻译:

当尝试向一个具有 observable 变量且包含一个初始值时, observable 的依赖通常当值真正的发生改变时才会被通知到,然而我们可以通过内置的通知拓展来达到当 observable’s 被修改时接受到通知,即使这个值是相同的。你可以通过运用拓展一个 observable 来达到目的。像下面代码一样:

myViewModel.personName.extend({ notify: 'always' }); 

举个例子:

<!DOCTYPE html> <html lang="en"> <head>  <meta charset="UTF-8">  <title>knoctoutJS测试</title>  <script type="text/javascript" src="js/knockout-3.3.0.debug.js"></script> </head> <body> The name is <span data-bind="text: personName"></span><br/> The name is <span data-bind="text: personAge"></span> <script type="text/javascript">  var myViewModel = {   personName: ko.observable('Bob'),   personAge: ko.observable(123)  };  myViewModel.personName.subscribe(function(newValue) {   alert("The person's new name is " + newValue);  });  myViewModel.personName('Bob');  ko.applyBindings(myViewModel); </script> </body> </html>  

首先我们给personName这个observable注册了一个事件,这个事件在值改变时触发,示例中,我们写入的值是一模一样的,都是‘Bob’,ko则默认为没有发生改变,那么注册的事件就不会触发了。但是通过上面的介绍的方法可以达到,即使写入的值是相同的,事件任然会触发。修改后的示例如下:

<!DOCTYPE html> <html lang="en"> <head>  <meta charset="UTF-8">  <title>knoctoutJS测试</title>  <script type="text/javascript" src="js/knockout-3.3.0.debug.js"></script> </head> <body> The name is <span data-bind="text: personName"></span><br/> The name is <span data-bind="text: personAge"></span> <script type="text/javascript">  var myViewModel = {   personName: ko.observable('Bob'),   personAge: ko.observable(123)  };  myViewModel.personName.extend({ notify: 'always' }); //注意这条语句    myViewModel.personName.subscribe(function(newValue) {   alert("The person's new name is " + newValue);  });    myViewModel.personName('Bob').personAge(123);   ko.applyBindings(myViewModel); </script> </body> </html>  
正文到此结束
Loading...