we are currently writing a new infrastructure for our MVC client and we are trying to make it so the developers will not need to right much Javascript (current development pool are mainly desktop based)
what I've done so far for our knockout scripts is create a Extension method that basicly generates all the knockout stuff based on the model using reflection.. this works perfectly fine for simple models with no computed values and so far as worked quite well.
so for example, say we had this class
public class AppViewModel
{
public string FirstName {get; set;}
public string LastName {get; set;}
}
the following would be generated and added to the view
function AppViewModel() {
this.firstName = ko.observable('Bob');
this.lastName = ko.observable('Smith');
}
what Id really like to do is support computed values from the model.. but I just cant figure out a way to do it
so
public FullName()
{
return this.FirstName + " " + this.LastNAme
}
would generate something like
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
So just to make it clear - what I'm trying to do is generate computed values based on my model.
thanks for any help
cheers.
ste.
further to what Pavel mentioned above, there is a great example showing your scenario to a 'T':
http://knockoutmvc.com/HelloWorld
here's a transcription from the page:
Model:
public class HelloWorldModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Expression<Func<string>> FullName()
{
return () => FirstName + " " + LastName;
}
}
Razor:
@using PerpetuumSoft.Knockout
@model KnockoutMvcDemo.Models.HelloWorldModel
@{
var ko = Html.CreateKnockoutContext();
}
<p>First name: @ko.Html.TextBox(m => m.FirstName)</p>
<p>Last name: @ko.Html.TextBox(m => m.LastName)</p>
<h2>Hello, @ko.Html.Span(m => m.FullName())!</h2>
@ko.Apply(Model)
Controller:
public class HelloWorldController : BaseController
{
public ActionResult Index()
{
InitializeViewBag("Hello world");
return View(new HelloWorldModel
{
FirstName = "Steve",
LastName = "Sanderson"
});
}
}
Autogenerated Html:
<p>
First name:
<input data-bind="value : FirstName" /></p>
<p>
Last name:
<input data-bind="value : LastName" /></p>
<h2>
Hello, <span data-bind="text : FullName"></span>!</h2>
<script type="text/javascript">
var viewModelJs = { "FirstName": "Steve", "LastName": "Sanderson" };
var viewModel = ko.mapping.fromJS(viewModelJs);
viewModel.FullName = ko.computed(function () {
try {
return this.FirstName() + ' ' + this.LastName();
}
catch (e) { return null; };
}, viewModel);
ko.applyBindings(viewModel);
</script>
Maybe it will help http://knockoutmvc.com/
Take a look at Script#
http://projects.nikhilk.net/ScriptSharp/
Try knockout JS official examples: http://knockoutjs.com/examples/
Knockout JS Tutorials : http://learn.knockoutjs.com/
Above links will help you in learning knockout JS.
Thanks,
-Naren