Custom Binding Handler, Binding Visualization from String Template

I am creating a special binding with a string pattern, which should be optional. If the user does not provide the template identifier, which I want to use by default, but it is not in the script tag in the body, this is just a string in the options literal.

How can I use a string as a template?

the default template should be really light, something like this

<span data-bind="text: name"></span> 

I tried ko.renderTemplate, but it only accepts id in script tags

 ko.renderTemplate(template, bindingContext.createChildContext(data), null, row, "replaceChildren"); 

Update Just received a notification about this issue and saw that there was a proposal from people introducing a template into the house and using the standard script tag provider. But this does not take into account that the user can override the default template source (a common scenario with single-layer applications. I use this method, which first tries to use the default template provider, and then returns a string like this to the template source

 var engines: {} var renderTemplate = function (element, template, data, bindingContext) { var engine = engines[template]; var success = false; do { try { ko.renderTemplate(template, bindingContext.createChildContext(data), engine, element, "replaceChildren"); success = true; engines[template] = engine; } catch(err) { if (engine != null) throw "Template engine not found"; engine = { templateEngine: stringTemplateEngine }; } } while (!success) }; 

The full code and stringTemplateEngine code can be found here https://github.com/AndersMalmgren/Knockout.Combobox/blob/master/src/knockout.combobox.js#L297

+4
source share
1 answer

To display patterns from strings, you will need to write your own template source, as described here.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1415371/


All Articles