Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KendoUI - can you create view models as functions

Tags:

mvvm

kendo-ui

With Knockout there are a couple of potential view model creation patterns, one is to use a literal:

var viewModel = {
    firstname: ko.observable("Bob")
};

ko.applyBindings(viewModel );

and the other is to use a function:

var viewModel = function() {
    this.firstname= ko.observable("Bob");
};

ko.applyBindings(new viewModel ());

As detailed in this question:

Difference between knockout View Models declared as object literals vs functions

My preference has always been to use a function because it essentially gives you a 'factory' allowing you to create multiple instances of the same view model.

With KendoUI, all the examples I have seen use a literal syntax:

var viewModel = kendo.observable({
     firstname: "Bob"
});

kendo.bind(document.body, viewModel);

My question is, with Kendo is it possible to emulate the Knockout style of view model creation via functions? This would allow me to create multiple instances of the same view model, add 'private' functions, etc ...

like image 213
ColinE Avatar asked Feb 17 '23 22:02

ColinE


1 Answers

After a bit of thought, I realised 'of course this is possible!' ...

ViewModel = function() {
     this.firstname = "Bob";

     return kendo.observable(this);
};

var viewModel = new ViewModel();

kendo.bind(document.body, viewModel);

Although you do have to be careful about references to 'this' within the constructor function because depending on when they are executed they may refer to the non-observable object:

ViewModel = function() {
     firstname = "Bob";

     this.doSomething = function() {
         // here 'this' does not point to an obervable, but 'that' does!
         that.set("forename", "Craig");
     }

     var that = kendo.observable(this);
     return that;
};

var viewModel = new ViewModel();

kendo.bind(document.body, viewModel);
like image 86
ColinE Avatar answered Mar 03 '23 23:03

ColinE