使用knockout.js将Click事件从一个视图模型传递到另一个视图模型

时间:2013-06-24 14:18:37

标签: mvvm knockout.js

我正在使用来自Knockout.JS网站(http://jsfiddle.net/rniemeyer/QSRBR/)的分页网格示例来构建网格。我在网格模板中声明了一个click事件,如下所示(click:goBackward): -

templateEngine.addTemplate("ko_negrid_navigation", "\
                    <div class=\"ko-grid-pageLinks\">\
                        <br/>\
                        <span><img src=\"/OCSENET/images/bluLeftNew.gif\" style=\"cursor:hand;\" alt=\"Backward\" data-bind='click: goBackward, visible: shouldShowBack'  /></span>\
                        <span>&nbsp;</span>\
                        <span><img src=\"/OCSENET/images/bluRightNew.gif\" style=\"cursor:hand;\" alt=\"Forward\"  data-bind='click: goForward, visible: shouldShowFwd'  /></span>\
                    </div>");

现在我需要在调用此Grid ViewModel的ViewModel中定义此goBackward方法,而不是在此Grid View模型中调用它自己。当我这样做时,事件不会触发goBackward()。我从另一个TestViewModel调用Grid,如下所示:

/*----------------------------------------------------------------------*/
/* TEST View Model
/*----------------------------------------------------------------------*/
function TESTViewModel() {
    var self = this;

    self.iRowFrom = ko.observable(1);
    self.iRowTo = ko.observable(5);
    self.gridRowCount = ko.observable(5);

    self.VM_AHISGrid;
    self.GridItems = ko.observableArray([]);    

    //fnDesignGrid
    self.fnDesignGrid = function () {
        self.VM_AHISGrid = new ko.NEGrid.viewModel({
            data: self.GridItems,
            columns: [
                        { headerText: "Address", rowText: "AHIS_Address" },
                        { headerText: "City", rowText: "AHIS_Addr_City" },
                        { headerText: "State", rowText: "AHIS_Addr_State" },
                        { headerText: "Zip", rowText: "AHIS_Addr_Zip" }
                    ],
            pageSize: self.gridRowCount(),
            gridName: 'ALST_NE_GRID'
        });
    }

    // I want this method to be triggered.
    self.goBackward = function () {
        alert('I m Backward')
    };  

}

2 个答案:

答案 0 :(得分:1)

好的,我修好了。非常简单,只需在调用viewmodel中定义方法,如下所示,它就像魅力一样。

self.NEGridViewModel.goBackward = function () {
        alert('I m Backward')
    };

答案 1 :(得分:0)

如果您的网格是视图模型的子网,那么在您的寻呼机模板中,您需要执行类似click: $parent.goBackwardclick: $root.goBackward的操作来绑定生活在更高范围级别的函数