Knockout使用ViewModel构造函数进行虚拟编写

时间:2013-04-12 17:51:31

标签: javascript knockout.js constructor durandal

我使用3对Views / ViewModels进行虚拟Knockout组合的一些奇怪功能

autoAttendant.js

define(['durandal/app', 'viewmodels/settings/autoAttendant/menu'], function(app, Menu){

    return function() {
        var self = this;

        self.attendant = ko.observable();

        self.activate = function() {
            self.autoAttendant(new Menu());
        };
    };
});

autoAttendant.html

<div id="content_pane" class="pushed_right">
    <div class="content_box">
        <h1>Attendant</h1>

        <!-- ko compose: 'viewmodels/settings/autoAttendant/menu' --><!--/ko-->

    </div>
</div>

menu.js

define(['durandal/app', 'viewmodels/settings/autoAttendant/menuItem'], function(app, MenuItem) {

    return function() {
        var self = this;

        self.menuItems = ko.observableArray([
            new MenuItem('val1', 'label1'),
            new MenuItem('val2', 'label2'),
            // etc...
        ]);
    };
});

menu.html

<div class="list">
    <div class="box_item master">
        <!-- html content -->
    </div>
    <!-- ko foreach: { data: menuItems } -->
        <!-- ko compose: 'viewmodels/settings/autoAttendant/menuItem' --><!--/ko-->
    <!-- /ko -->
</div>

menuItem.js

define(['durandal/app'], function(app) {
    var menuItem =  function(val, label, active) {
        var self = this;

        console.log('val:', val, 'label:', label, 'active:', active); // purely for testing purposes

        var _val = val || 'default_val',
            _label = label || 'default_label',
            _active = active || false;

        self.val = ko.observable(_val);
        self.label = ko.observable(_label);
        self.active = ko.observable(_active);
    };
    return menuItem;
});

menuItem.html

<div class="level">
    <div class="box_item clickable">
        <!-- html content -->
    </div>
</div>

这些表示设置中的单个页面,显示菜单和菜单的子项目。

菜单和MenuItem 必须从话务员View / ViewModel分离,因为菜单本身是递归的,而menuItem可以链接到具有自己的menuItems的子菜单。

问题出现在第二个ko composeconsole.log发生了3次,前2次显示了menu.js中MenuItem构造函数的正确传递参数:

val: val1 label: label1 active: undefined

在最后console.log打印输出时,已经传递的参数会被覆盖:

val: <!-- ko compose: 'viewmodels/settings/autoAttendant/menuItem' --><!--/ko--> label: Object {model: "viewmodels/settings/autoAttendant/menuItem", bindingContext: L.b.z, activeView: null} active: undefined

为什么会这样?

1 个答案:

答案 0 :(得分:0)

以下工作,经过对源头的深入研究和(不仅仅是)一点点实验:

<!-- ko compose: {view:'settings/autoAttendant/menuItem'} --><!--/ko-->

来自Durandal docs on compose