依我個人觀點,hasfocus繫結的實用性較低,但應該還是有適用的場合。簡單地說,它可以將Boolean屬性繫結到可取得輸入焦點的HTML元素上(例如: TextBox、CheckBox、RadioButton、Select、Button...)形成雙向繫結,當元素取得焦點時,ViewModel屬性會被更新為true;若屬性值被改為true,輸入焦點也會移至元素上。

範例11簡單展示其運作原理: 線上展示

網頁上有兩個<input type="text">,姓名輸入欄繫結到ViewModel的nameFocus屬性,點選姓名欄準備輸入時,後方的<span>被設為data-bind="visible: nameFocus",故會在姓名欄取得焦點時顯示"* 請輸入姓名"字樣。點選積分欄位,姓名欄後方字樣則會消失。網頁上有個Set Focus按鈕,按下後會將ViewModel.nameFocus設為true,此時可觀察到焦點又回到姓名欄位,驗證其為雙向繫結無誤!

程式碼如下:

<!DOCTYPE html>
 
<html>
<head>
    <title>Lab 11 - hasfocus繫結</title>
    <script src="../Scripts/jquery-1.7.2.js"></script>
    <script src="../Scripts/knockout-2.1.0.debug.js"></script>
    <script>
        function MyViewModel() {
            var self = this;
            self.name = ko.observable();
            self.score = ko.observable();
            self.nameFocus = ko.observable(false);
            self.setFocus = function () {
                self.nameFocus(true);
            };
        }
 
        $(function () {
            ko.applyBindings(new MyViewModel());
        });
    </script>
    <style>
        body, input
        {
            font-size: 10pt;
            line-height: 25px;
        }
    </style>
</head>
<body>
姓名: <input type="text" data-bind="hasfocus: nameFocus, value: name" />
<span data-bind="visible: nameFocus">* 請輸入姓名</span>
<br />
積分: <input type="text" data-bind="value: score" />
<br />
<input type="button" value="Set Focus" data-bind="click: setFocus" />
nameFocus=<span data-bind="text: nameFocus"></span>
</body>
</html>

[KO系列]

http://www.darkthread.net/kolab/labs/default.aspx?m=post

Comments

# by sleepycat

self.nameFocus(ture); <-- true?

# by Jeffrey

to sleepycat, 感謝您的細心指正,原程式有誤,已更正。

# by Mike

data-binding="value: score" binding??

# by Jeffrey

to Mike, 感謝指正。(看到還有人在研究KO,好感動!)

Post a comment


87 - 26 =