I’m wondering if there’s a way to apply binding to some DOM elements without re-rendering the DOM elements.
I ask because in my situation, the server is returning me the HTML build with Razor templates. So the backend handles all the DOM building.
All I want to do is take a fully rendered markup and apply some sort of binding to it, using a robust JS library such as Knockout.js. Is this at all possible.
So for example in normal client side built markup I would do something like this:
<ul data-bind="foreach: fruits">
<li data-bind="text: name"></li>
</ul>
Then apply bindings and built html.
ko.applyBindings(new ViewModel(data));
Which will result in something like this:
<ul data-bind="foreach: fruits">
<li data-bind="text: name">Apples</li>
<li data-bind="text: name">Pairs</li>
<li data-bind="text: name">Banana</li>
<li data-bind="text: name">Peaches</li>
<li data-bind="text: name">Grapes</li>
</ul>
But using Razor templates the HTML is returned like this already but I still want to apply bindings. How do I do this without re-rendering the html. The only other way I can think of is too build my own custom bindings but I want to avoid that.
Is there another framework I could use that does just this? I heard backbone could possibly do this.
As some of the other respondents have said, I think you’re better off doing this a different way. IF you’d rather avoid the additional server round trip of an Ajax call to get the data, you could get the server to render a JSON string representing your data, and embed that in your HTML alongside the HTML template.
You could then use JSON.parse to parse this string into a JSON tree and bind those values into your view model in the view model’s constructor.
That way you’ll get the performance boost of returning the data from the server as part of the response, but without bending Knockout out of shape. As an added bonus, adding AJAX behaviour to e.g. Update this data becomes much easier.