knockoutjs關於ko.bindingHandlers的updata訂閱

ko.bindingHandlers是先執行init進行初始化數據的綁定(若是須要執行updata進行數據更新能夠不用初始化);javascript

1 init: function(element, valueAccessor) {
2                     //初始化數據--而後執行updata進行須要更新數據的綁定,添加訂閱
3                     //若是在updata進行了數據的執行,init能夠添加初始化事件
4                     var value = valueAccessor(); // Get the current value of the current property we're bound to
5                     $(element).text(value); // jQuery will hide/show the element depending on whether "value" or true or false
6                 },
ko.bindinHandlers.init

在updata裏面,纔是訂閱產生的時候,而不是在init的時候,數據就綁定了訂閱;html

1 update: function(element, valueAccessor, allBindings) {
2                     var value = ko.unwrap(valueAccessor()); //執行更新數據綁定,必需要執行一次不然沒法肯定添加訂閱
3                     //var value = valueAccessor()(); // Get the current value of the current property we're bound to
4                     $(element).text(value);
5                 }
ko.dindingHandlers.updata

完整代碼以下:java

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/jquery-2.1.0.js"></script>
        <script type="text/javascript" src="js/knockout-3.4.0.debug.js"></script>
        <script type="text/javascript">
            ko.bindingHandlers.slideVisible = {
                init: function(element, valueAccessor) {
                    //初始化數據--而後執行updata進行須要更新數據的綁定,添加訂閱
                    //若是在updata進行了數據的執行,init能夠添加初始化事件
                    var value = valueAccessor(); // Get the current value of the current property we're bound to
                    $(element).text(value); // jQuery will hide/show the element depending on whether "value" or true or false
                },
                update: function(element, valueAccessor, allBindings) {
                    var value = ko.unwrap(valueAccessor()); //執行更新數據綁定,必需要執行一次不然沒法肯定添加訂閱
                    //var value = valueAccessor()(); // Get the current value of the current property we're bound to
                    $(element).text(value);
                }
            };
            var model = {
                te: ko.observable("ttttttttt"),
                aaa: function() {
                    this.te("aaaaaaaaaaaaaaaaaaaa");
                }
            }
            window.onload = function() {
                ko.applyBindings(model, document.body)
            }
        </script>
    </head>

    <body>
        <div data-bind="slideVisible:te"></div>
        <input type="button" value="aaaaaaaaa" data-bind="click:aaa" />
    </body>
</html>
ko.bindingHandlers.model

注:小七目前仍是小白,寫的博客爲筆記類型的博客,是在項目中遇到的問題,僅用於學習。jquery

  涉及到原理部分還未作總結。app

  若是內容有不對、不全面或者其餘的問題,歡迎你們糾正。ide

相關文章
相關標籤/搜索