Knockout學習筆記之二($root,$parent及$data的區別)

如下是我從Google上找到的一個例子,很是生動形象,我修改了部分代碼,具體內容以下:javascript

對於$root 與$parent的區別:html

  • $root refers to the view model applied to the DOM with ko.applyBindings;

        譯:$root 是指ViewModel所應用於ko.applyBindings時所使用的DOM;java

  • $parent refers to the immediate outer scope;

    譯:$parent 是指當前DOM元素直接的外部父類(只有一層);app

Or, visually, from $data's perspective:ide

 

 

Or, in words of the relevant documentation:ui

  • $parent: This is the view model object in the parent context, the one immeditely outside the current context.
  • $root: This is the main view model object in the root context, i.e., the topmost parent context. It’s usually the object that was passed to ko.applyBindings. It is equivalent to $parents[$parents.length - 1].

對於三者的區別($root,$parent及$data):this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title></title>
    <script type="text/javascript" src="knockout-3.4.0.js"></script>
    <style>
        th, td {
            padding: 10px;
            border: 1px solid gray;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            vm.mainPerson(grandpa);
            grandpa.children.push(daddy);
            daddy.children.push(son1);
            daddy.children.push(son2);
            ko.applyBindings(vm);
        }
        
        var Person = function (name) {
            var self = this;
            self.name = ko.observable(name);
            self.children = ko.observableArray([]);
        }

        var ViewModel = function () {
            var self = this;
            self.name = 'root view model';
            self.mainPerson = ko.observable();
        }

        var vm;
        vm= new ViewModel(),
        grandpa = new Person('grandpa'),
        daddy = new Person('daddy'),
        son1 = new Person('marc'),
        son2 = new Person('john');
    </script>
    <script type="text/html" id="person">
        <tr>
            <td data-bind="text: $root.name"></td>
            <td data-bind="text: $parent.name"></td>
            <td data-bind="text: $data.name"></td>
        </tr>
        <!-- ko template: { name: 'person', foreach: children } --><!-- /ko -->
    </script>

    <table>
        <tr>
            <th>$root</th>
            <th>$parent</th>
            <th>$data</th>
        </tr>
        <!-- ko template: { name: 'person', data: mainPerson } --><!-- /ko -->
    </table>
</head>
<body>
</body>
</html>
View Code

具體頁面呈現:spa

The $root is always the same. The $parent is different, depending on how deeply nested you are.3d

譯:$root常常是相同的,而$parent是不一樣的,而這種不一樣主要取決於你嵌套的深度。code

相關文章
相關標籤/搜索