KnockoutJS -啟用繫結



此繫結用於根據指定條件啟用某些基於 DOM 元素。這對於表單元素(如inputselecttextarea)非常有用。

語法

enable: <binding-value>

引數

  • 引數包含布林值型別的數值,決定是否啟用元素。如果引數為真值或類似真值,則啟用元素。

  • 非布林值被視為鬆散的布林值。這意味著 0 和 null 被視為類似假的值,而整數和非 null 物件被視為類似真的值。

  • 如果引數中的條件包含任何可觀察值,則每當可觀察值更改時,都會重新評估條件。相應地,相關標記將根據條件結果啟用。

示例

讓我們來看下面的例子,它演示了啟用繫結的使用方法。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Enable Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p> Enter your feedback here:<br><br>
         <textarea rows = 5 data-bind = "value: hasFeedback, 
            valueUpdate: 'afterkeydown'" ></textarea>
      </p>
      
      <p><button data-bind = "enable: hasFeedback">Save Feedback</button></p>

      <script type = "text/javascript">
         function ViewModel () {
            hasFeedback = ko.observable('');
         };

         var vm = new ViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟來檢視上述程式碼是如何工作的:

  • 將上述程式碼儲存到enable-bind.htm檔案中。

  • 在瀏覽器中開啟此 HTML 檔案。

  • 只有當用戶輸入反饋後,“儲存”按鈕才會啟用。

使用隨機表示式實現啟用繫結

您還可以使用隨機表示式來決定是否啟用元素。

示例

讓我們來看下面的例子,它演示了使用隨機表示式呼叫啟用繫結的使用方法。

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Enable binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Below button will be enabled only when product stock is available.</p>
      <button data-bind = "enable: productStock() > 0 ">
         Product Details
      </button>

      <script type = "text/javascript">
         function AppViewModel() {
            this.productStock = ko.observable(-10);
         };
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟來檢視上述程式碼是如何工作的:

  • 將上述程式碼儲存到enable-random-bind.htm檔案中。

  • 在瀏覽器中開啟此 HTML 檔案。

  • 只有當產品庫存可用時,“產品詳情”按鈕才會啟用。

knockoutjs_declarative_bindings.htm
廣告
© . All rights reserved.