2013-02-04 29 views
2

如何計算函數this.followButtonText不更新,始終顯示(Follow),何時可觀察this.isFollowing發生更改? 。 $(文件)。就緒(函數(){Knockouts ko.computed變量在更改obserable時不會更新

 function AppViewModel() { 

      this.toggleIsFollowing = function() { 
       this.isFollowing = !this.isFollowing; 
       follow(); 
      }; 

      this.isFollowing = ko.observable(false); 
      this.followButtonText = ko.computed(function() { 
       return this.isFollowing ? "Unfollow" : "Follow"; 
      }); 
     } 

     ko.applyBindings(new AppViewModel()); 


     } 

    }); 
</script> 

回答

2

可觀察到的實際上是一個函數來讀取電流值,你需要調用它與像沒有參數的函數:this.isFollowing()

要設置observable的值,您需要將新值作爲第一個參數傳遞,因此,您的切換將如下所示:this.isFollowing(!this.isFollowing());

在您的followButtonText計算中,您需要將它作爲函數調用如:

return this.isFollowing() ? "Unfollow" : "Follow";

+0

啊,謝謝你忘了那些! – Nikos

2

更改此聲明:return this.isFollowing? 「取消關注」:「關注」;

對此:return this.isFollowing()? 「取消關注」:「關注」;

括號稱它爲一個函數,這是爲了獲得最新值