Knockout自訂綁定建立方法_javascript技巧

來源:互聯網
上載者:User

概述

除了上一篇列出的KO內建的綁定類型(如value、text等),你也可以建立自訂綁定。

註冊你的binding handler

ko.bindingHandlers.yourBindingName = {  init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {    // This will be called when the binding is first applied to an element    // Set up any initial state, event handlers, etc. here  },  update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {    // This will be called once when the binding is first applied to an element,    // and again whenever any observables/computeds that are accessed change    // Update the DOM element based on the supplied values here.  }}; 

接下來你就可以在任意dom元素上使用的自訂綁定了:

<div data-bind="yourBindingName: someValue"> </div> 

注意:你不必在你的handler裡把init和update的callback都提供,可以提供任意一個。

update callback

顧名思義,當你的監控屬性observable更新的時候,ko會自動調用你的update回調。

它有以下參數:

    element:使用這個綁定的dom元素;

    valueAccessor  : 通過調用valueAccessor()可以獲得當前綁定的model屬性值,調用ko.unwrap(valueAccessor())能夠更方便的擷取observable的值和普通值;

    allBindings : 綁定到這個dom元素上的model的所有屬性值,例如調用callBindings.get('name') 返回綁定的name屬性值(不存在返回undefined),或者調用allBindings.has('name')判斷name是否綁定到了當前的dom中;

    viewModel  : 在Knockout.3x中以棄用,可用bindingContext.$data或者bindingContext.$rawData來擷取當前的viewModel;

   bindingContext  : 綁定上下文,可調用bindingContext.$data、 bindingContext.$parent, bindingContext.$parents等擷取資料;

接下來看一個例子,你也許希望使用visible綁定來控制元素的可見度,並且加上動畫效果,這時你可以建立你的自訂綁定:

ko.bindingHandlers.slideVisible = {  update: function(element, valueAccessor, allBindings) {    // First get the latest data that we're bound to    var value = valueAccessor();    // Next, whether or not the supplied model property is observable, get its current value    var valueUnwrapped = ko.unwrap(value);    // Grab some more data from another binding property    var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified    // Now manipulate the DOM element    if (valueUnwrapped == true)      $(element).slideDown(duration); // Make the element visible    else      $(element).slideUp(duration);  // Make the element invisible  }}; 

然後你可以這樣使用這個自訂綁定:

<div data-bind="slideVisible: giftWrap, slideDuration:600">You have selected the option</div><label><input type="checkbox" data-bind="checked: giftWrap" /> Gift wrap</label><script type="text/javascript">  var viewModel = {    giftWrap: ko.observable(true)  };  ko.applyBindings(viewModel);</script> 

init callback

ko將為每個使用綁定的dom元素調用你的init函數,它有兩個主要用途:

(1)為dom元素設定初始化狀態;

(2)註冊一些事件處理常式,例如:當使用者點擊或者修改dom元素時,你可以改變監控屬性的狀態;

ko將使用和update回調完全相同一組參數。

繼續前面的例子,你也許想讓slideVisible在頁面第一次顯示的時候就設定該元素的可見度狀態(沒有任何動畫效果),而動畫效果是在以後改變的時候執行,你可以按照下面的方式來做:

ko.bindingHandlers.slideVisible = {  init: function(element, valueAccessor) {    var value = ko.unwrap(valueAccessor()); // Get the current value of the current property we're bound to    $(element).toggle(value); // jQuery will hide/show the element depending on whether "value" or true or false  },  update: function(element, valueAccessor, allBindings) {    // Leave as before  }}; 

giftWrap被初始化定義為false(ko.observable(false)),關聯的DIV會在初始化的時候隱藏,之後使用者點擊checkbox時才讓DIV顯示。

你現在已經知道如何使用update回調了,當observable值改變的時候你可以更新dom元素。我們現在可以用另外的方法來做,比如當使用者有某個action操作時,也能引起你的observable值更新,例如:

ko.bindingHandlers.hasFocus = {  init: function(element, valueAccessor) {    $(element).focus(function() {      var value = valueAccessor();      value(true);    });    $(element).blur(function() {      var value = valueAccessor();      value(false);    });  },  update: function(element, valueAccessor) {    var value = valueAccessor();    if (ko.unwrap(value))      element.focus();    else      element.blur();  }}; 

現在你可以通過元素的“focusedness”綁定來讀寫你的observable值了。

<p>Name: <input data-bind="hasFocus: editingName" /></p><!-- Showing that we can both read and write the focus state --><div data-bind="visible: editingName">You're editing the name</div><button data-bind="enable: !editingName(), click:function() { editingName(true) }">Edit name</button><script type="text/javascript">  var viewModel = {    editingName: ko.observable()  };  ko.applyBindings(viewModel);</script>

以上內容是小編給大家分享的Knockout自訂綁定建立方法,希望大家喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.