Hi,
I have had a similar issue where I need to wire-up my page, and parts
of the view model may not be available. I solved it by binding to the
dom elements directly, but I never liked that solution because it
seems like a deviation from the pattern -Meaning that suddenly there
was this interim bit of code that did not fit in the view model
because it was aware of the views, and also was bound to identifiers
on the view itself, so I could not bind to 2 seperate dom elements
without some code changes to this pseudo view model layer-
I have been working on an 'each' iterator binder based on Brian Beck's
'bind' handler, (which I renamed in my project to 'dataContext') and
when I saw your post I realized I could solve my problem with a small
change to the dataContext binder that I called dynamicDataContext. I
posted the code here:
https://github.com/lancewynn/My-knockout-bindings
but I don't know when it will appear...
anyhow, you can perhaps use it like this for your problem:
in the below snippit, I have a viewmodel that is an empty object, I
applyBindings on that view model. In my view I specified a div that
uses the dynamicDataContex binder. After the bindings are applied, I
can set the dynamicModel to the viewModel's dynamicProperty, and the
binder will handle everything from there. It seems like a pretty
slick solution, and seems to me that it follows the pattern a little
better. you'll still have to follow some naming conventions as far as
the property names of the dynamic properties, but it doesn't care if
you inject the additional view models before or after the initial
applyBindings call. Also, it makes the view a bit cleaner in my
opinion.
<body>
<script type="text/javascript">
$(function () {
viewModel = {
};
ko.applyBindings(viewModel);
dynamicModel = { dynamicName: 'Dynamic viewModel' };
viewModel.dynamicProperty(dynamicModel);
});
</script>
<div data-bind="dynamicDataContext: 'dynamicProperty'">
<span data-bind="text: dynamicName"></span>
</div>
</body>
second sample showing the viewmodel being applied prior to the initial
applyBindings:
<body>
<script type="text/javascript">
$(function () {
viewModel = {
};
dynamicModel = { dynamicName: 'Dynamic viewModel' };
viewModel.dynamicProperty = dynamicModel;
ko.applyBindings(viewModel);
});
</script>
<div data-bind="dynamicDataContext: 'dynamicProperty'">
<span data-bind="text: dynamicName"></span>
</div>
</body>