2013-06-26 431 views
2

我有一個基礎視圖模型如下:的Javascript knockout.js功能覆蓋

var myApp = myApp || {}; 

myApp.BaseViewModel = function() { 
    self = this; 
    self.var1 = ko.observable(); 
    self.messageToSay = Function() { 
     alert("in Base view model"); 
    }; 
    self.sayMessage = function() { 
     self.messageToSay(); 
    } 
}; 

而且我從BaseViewModel繼承如下一個視圖模型:

var myApp = myApp || {}; 

myApp.HomeViewModel = function() { 

    var self = this; 
    ko.utils.extend(self. new myApp.BaseviewModel()); 

    self.messageToSay = Function() { 
     alert("in Home view model"); 
    }; 

}; 

var vm = new myApp.HomeViewModel(); 
ko.applyBindings(vm, vm); 

的問題是,當我執行vm.sayMessage()總是返回「在基本視圖模型中」而不是「在主視圖模型中」。如何獲取HomeViewModel中的messageToSay()方法以覆蓋BaseViewModel()中的方法?

感謝 馬丁

回答

2

這是你應該執行的傳承方式:我希望它能幫助

myApp.HomeViewModel = function() { 

    var self = this; 
    myApp.BaseviewModel.apply(self, [/*BaseViewModel constructor args */]); 

    self.messageToSay = function() { 
     alert("in Home view model"); 
    }; 

}; 

See fiddle