0

Possible Duplicate:
Difference between knockout View Models declared as object literals vs functions

I am working in Knowckout MVVM framework and I am new to it. I have been using it for last one and a half months and it has been decent so far. Now, all the examples that I saw on the web and everywhere else define viewmodel as something like a Object variable with a declaration like below:

var ViewModel = {};

that was comletely understandable.BUT

lately I have seen some codemodels in which it is declared as a function:

somehting like

var ViewModel = function(){
self = this;

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

}

Not only that, when the view model is actually used, they have to instantiate the viewmodel.

I see it as complete new way to represent viewmodel and I am failing to see how it is better than conventional ViewModel declaration approach.

Can someone please throw some light on this?

Community
  • 1
  • 1
Lost
  • 12,007
  • 32
  • 121
  • 193

2 Answers2

1

This answer explains the difference betweeen using an object literal and a function for defining a view model: Difference between knockout View Models declared as object literals vs functions

Community
  • 1
  • 1
RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211
0

It is better because entire logic of a ViewModel can be contained in (encapsulated by) this constructor function. Logic can be very complex. It can include definitions of new functions and variables that are not global anymore.

I find following pattern:

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)
    };

})());

to be even better because it doesn't introduce any new global variable (like constructor function) and still has great encapsulation capabilities.

Stipo
  • 4,566
  • 1
  • 21
  • 37