2013-07-24 77 views
1

我有結構的單頁應用:knockoutjs調用函數在子視圖模型從根視圖模型定義

  • 視圖模型-RootVM(頁面頁眉,頁腳,常用功能,...):
    • SubModelA(第1頁 - 模板)
    • SubModelB(第2頁 - 模板)

我想調用從頁頭(ViewModel-RootVM)在頁面2(SubModelB)上定義的函數fnTest。我怎麼能從ViewModel和HTML做到這一點?這甚至有可能嗎?如果是這樣,請以示例幫助我。我有點迷失在這裏。

我使用knockoutjs V2.2.1和jQuery v1.9.1的

視圖模型(你可以看到的jsfiddle代碼的其餘部分,下面的鏈接)

var View = function(title, templateName, data) { 
     var self = this; 


    self.title = title; 
    self.templateName = templateName; 
    self.data = data; 

    self.myPostProcessingLogic = function(element1, index1, data1) { 
     console.log('post processing'); 
    }; 
}; 

var SubModelA = function(root) { 
    var self = this; 

    self.items = ko.observableArray([ 
     { id: 1, name: "one" }, 
     { id: 2, name: "two" }, 
     { id: 3, name: "three" } 
     ]); 
}; 

var SubModelB = function(root) { 
    var self = this; 

    self.firstName = ko.observable("Bob"); 
    self.lastName = ko.observable("Smith"); 

    self.fnTest = function() { 
     alert('calling function from subModelB'); 
    }; 

    self.fnSubModelB = function() { 
     root.allert('calling function allert from root'); 
    }; 
}; 

var ViewModel = function() { 
    var self = this; 

    self.views = ko.observableArray([ 
     new View("one", "oneTmpl", new SubModelA(self)), 
     new View("two", "twoTmpl", new SubModelB(self)) 
     ]); 

    // default open page 'two' 
    self.selectedView = ko.observable(self.views()[1]); 

    self.allert = function() { 
     alert('alert from rootVM'); 
    }; 

    self.allert2 = function() { 
     // how can I call function 'fnTest' which is defined in SubModelB 
     self.views()[1].fnTest(); // this is not working 
    }; 
}; 

var viewModel = new ViewModel(); 
ko.applyBindings(viewModel); 

link to jsfiddle

回答

1

這不起作用,因爲fnTest()沒有在「視圖」中聲明,而是在其「數據」中聲明。它的工作原理使用:

self.views()[1].data.fnTest() 

在這裏看到:http://jsfiddle.net/LJBqp/

+0

juhuhu,你只要讓我很快樂。謝謝! – grajsek