Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

View Model definition as literal object OR as constructor function

777 views
Skip to first unread message

Alexander Biryukov

unread,
Aug 9, 2011, 10:24:52 PM8/9/11
to knock...@googlegroups.com
Hi guys!

Could anyone explain me pros and cons of using KO View Model as literal object and as constructor function?
Where is the difference? In which cases I should use one or another variant?

I explain what I mean.
/**
 *First variant:  View Model as literal object:
 */
ViewModel = {
    firstName: ko.observable('John'),
    lastName: ko.observable('Smith'),
};

ViewModel.fullName = ko.dependingObservable(function () {
// Some code here
}, ViewModel);

ko.applyBindings(ViewModel);

/**
 * Second variant: View Model as constructor function
 */
function ViewModel() {
    this.firstName = ko.observable('John'),
    this.lastName = ko.observable('Smith'),

    this.fullName = ko.dependingObservable(function () {
        // Some code here
    }, this);  
};

ko.applyBindings(new ViewModel());

Thanks!

Mark Hahn

unread,
Aug 9, 2011, 10:41:26 PM8/9/11
to knock...@googlegroups.com
I can't imagine any difference.  The resulting object is the same except for a prototype property.

Alexander Biryukov

unread,
Aug 10, 2011, 10:56:19 PM8/10/11
to knock...@googlegroups.com
Hi Mark!

Thanks for the response.

Any thoughts?

Regards,
Alex.

thiag...@gmail.com

unread,
Nov 19, 2012, 4:43:44 PM11/19/12
to knock...@googlegroups.com
I'm also trying to understand the pros and cons of each one.

rpn

unread,
Nov 19, 2012, 5:08:33 PM11/19/12
to knock...@googlegroups.com, thiag...@gmail.com

thiag...@gmail.com

unread,
Nov 19, 2012, 5:24:41 PM11/19/12
to knock...@googlegroups.com, thiag...@gmail.com
Thanks rpn. I was suspecting that functions was the better approach.
Reply all
Reply to author
Forward
0 new messages