0
votes

i'm working in a project that requires Asp.Net WebForms (is a migration of a huge .net 2.0 site with no time to reimplement in MVC) and asmx web services. When a page is requested is sent by the server and works like a SPA. After a while we realize that we need a model behind the javascript to avoid a nightmare code. We tried Knockout.js until we hit a problem that we couln't solve: Code reuse with User Controls and Knockout.js View Models. Our user controls has viewmodels that when several user controls are combined in a page. Knockout simply doesn't work. I know that maybe webforms are not the tipical stack when making SPA web apps, but well... requirements are requirements.... any help?

1
When you apply a viewmodel to the page, you can apply a knockout view model only to a portion of the page by doing ko.applyBindings(viewModel, document.getElementById("DIVwrapperaroundusercontrolmarkup"));Brian Mains

1 Answers

0
votes

What I'd do, in your scenario (because I've done it myself in the past):

Have a global ViewModel object, say:

var _ViewModel = {}

For each of your controls, have a function that sets up that portion of the ViewModel, i.e. (this goes in .ascx and points to a JS file function)

<script language="javascript">
var _ViewModel // this should be in a global.js file or something.
SetupThisViewModel()
ko.applyBindings(_ViewModel);
</script>

and in JS file:

// Used for user  control 1
function SetupThisViewModel()
{
    _ViewModel.testItem = ko.observable('');
}

// Used for user control 2
function SetupThisViewModel2()
{
    _ViewModel.testItem2 = ko.observable('');
}

And, if you want two user controls on one page, just do:

<script language="javascript">
    var _ViewModel // this should be in a global.js file or something.
    SetupThisViewModel();
    SetupThisViewModel2();
    ko.applyBindings(_ViewModel);
    </script>

This will work for your scenario.