I am currently working on an ASP.NET MVC solution and have recently introduced both Knockout (an MVVM JS library) and Wijmo (a set of jQuery UI widgets).
With the introduction of Knockout I also need to have models on the client side, so for this purpose I am serializing the C# ViewModel and attaching it to the view using data-model="@Model.ToJson()"
. This allows me to retrieve the model from JS and apply some client-side love to everything.
However, knockout needs everything to be observables, so I need to declare a separate client-side ViewModel and map everything from the data-model object. This feels very much like duplicate effort and I'd like to avoid it somehow.
I'm hoping someone has a tool or technique to share that will allow me to render the knockout ViewModel directly from the server. Possible solution could include:
I'd like the solution to be generic and automatic, as my current approach of typing the observable client-side view models by hand is just too unproductive to be viable.
How are you solving this problem?
According to their tutorials it's just a simple .map
function
If this is the ViewModel
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
And this function get's the data from the server, it uses the .map
function to inject the server data right into the VM
// Data
var self = this;
self.tasks = ko.observableArray([]);
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) {
return new Task(item)
});
self.tasks(mappedTasks);
});
For ko mapping http://knockoutjs.com/documentation/plugins-mapping.html
For auto-bind here's an example
https://groups.google.com/forum/#!msg/knockoutjs/IJTx37UXQVw/UTrWdEK1C-oJ
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