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 ...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With