knockout / knockout

Knockout makes it easier to create rich, responsive UIs with JavaScript
http://knockoutjs.com/
Other
10.43k stars 1.52k forks source link

Need an 'attach' event for the template binding/renderTemplate() #1642

Open mstarets opened 9 years ago

mstarets commented 9 years ago

This request is very similar to issue #1456 (now closed). We would like to be able to execute script after the template has been attached to the parent node, but before the bindings have been activated:

if (haveAddedNodesToParent) {
    // Execute an 'attach' callback here
    activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
    if (options['afterRender'])
        ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
}

We need to execute some sizing code as soon as possible after the template is inserted, so doing this in afterRender callback is not an option. We understand that this could be achieved by adding a custom binding on the top-level node for each template, but this is undesirable because we have lots of templates that loaded from external sources with Knockout AMD Helpers.

brianmhunt commented 9 years ago

Would adding binding preprocessing for the template help, like this:

ko.bindingHandlers.template.preprocess = function(stringFromMarkup) {
  // do your stuff
  return stringFromMarkup;
}

Another option is to overload the template.init e.g.

var original_template_init = ko.bindingHandlers.template.init;
ko.bindingHandlers.template.init = funciton () {
   // do your stuff
   original_template_init.apply(this, arguments);
}

Do either of those techniques help?

mstarets commented 9 years ago

Brian,

Thank you for looking at this issue. Overriding template.init won't work because init() gets called before the template DOM is inserted into the target node. Binding preprocessing would occur too soon as well: I need my callback to be invoked just before the first binding within the inserted template is applied, and not just before the template binding itself is applied.

Thanks, Max

brianmhunt commented 9 years ago

Ah yes I see. (I'm catching on ... it might take a while, but I'll get there :grin:) Have to mull this a bit. :)

mstarets commented 9 years ago

Jut one more piece of information: the attach event is supported by Durendal, so adding it would allow some Durendal customers to switch to using core Knockout template support and Knockout Components.