Sharma K
Sharma K

Reputation: 107

Passing Click Event from within one view model to another view model using knockout.js

I'm using the Paged Grid Sample from Knockout.JS Site (http://jsfiddle.net/rniemeyer/QSRBR/) to build a grid. I declared a click event inside the grid template like below (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>");

Now I need to define this goBackward method inside a ViewModel that calls this Grid ViewModel rather than inside this Grid View Model it-self. When I do this the event is not triggering the goBackward(). I m calling the Grid from another TestViewModel as below:

/*----------------------------------------------------------------------*/
/* 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')
    };  

}

Upvotes: 2

Views: 619

Answers (2)

Sharma K
Sharma K

Reputation: 107

Ok, I fixed it. Pretty simple, just define the method in calling viewmodel as below and it works like charm.

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

Upvotes: 1

RP Niemeyer
RP Niemeyer

Reputation: 114792

If your grid is a child of your view model, then in your pager template, you would need to do something like click: $parent.goBackward or click: $root.goBackward to bind against a function that lives at a higher scope level.

Upvotes: 0

Related Questions