2012-09-23 41 views
0

可能重複:
Difference between knockout View Models declared as object literals vs functions是viewModel函數還是對象變量?

我在Knowckout MVVM框架工作,我是新來的吧。過去的一個半月我一直在使用它,到目前爲止它一直體面。現在,我在網絡上看到,到處的所有例子中其他定義視圖模型,就像這樣一個對象變量,聲明如下圖所示:

var ViewModel = {}; 

這是comletely understandable.BUT

最近我已經看到了一些codemodels在聲明它作爲一個功能:

服用點像

var ViewModel = function(){ 
self = this; 

// some code in conventions with var member = {} instead of member:{} 

} 

不僅如此,當視圖模型是實際使用d,他們必須實例化視圖模型。

我認爲這是一種全新的方式來表示viewmodel,我無法看到它比傳統的ViewModel聲明方式更好。

有人可以對此有所瞭解嗎?

回答

0

這是更好,因爲一個ViewModel的整個邏輯可以被包含在(由包封的)這個構造函數。邏輯可能非常複雜。它可以包含新功能的定義和不再是全局的變量。

我發現下面的模式:

ko.applyBindings((function() { 

    // Define local variables and functions that view model instance can access and use, 
    // but are not visible outside this function. 

    var firstName = ko.observable("John"); 
    var lastName = ko.observable("Doe"); 

    var getFullName = function() { 
     return firstName() + " " + lastName(); 
    }; 

    // Return view model instance. 
    return { 
     fullName : ko.computed(getFullName) 
    }; 

})()); 

要更爲出色,因爲它不引入任何新的全局變量(比如構造函數),並且仍然具有很大的封裝能力。

相關問題