KendoUI - you can create presentation models as functions

With knockout, there are several models for creating a potential representation model, one is to use a literal:

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

and the other is to use the function:

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

As detailed in this question:

The difference between knockout View models declared as object literals versus functions

My preference has always been to use a function because it essentially gives you a "factory" that allows you to create multiple instances of the same representation model.

With KendoUI, all the examples I've seen use literal syntax:

 var viewModel = kendo.observable({ firstname: "Bob" }); kendo.bind(document.body, viewModel); 

My question is: with Kendo, is it possible to emulate the style of creating a knockout style using functions? This would allow me to create multiple instances of the same presentation model, add 'private' functions, etc.

+4
source share
1 answer

After some thought, I realized: “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 should be careful with references to 'this' inside the constructor function, because depending on when they are executed, they may refer to an unobservable 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); 
+8
source

All Articles