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

Bugfix: Error when calling ko.bindingEvent.subscribe( 'childrenComplete' ) before applyBindings has reached the node. #2584

Open Griffork opened 2 years ago

Griffork commented 2 years ago

I wanted to know when a given node had finished being initialised (along with it's children) and tried to call it before applyBindings had reached the node in question, and proceeded to get a syntax error in knockout core instead of setting up a subscription properly.

My code:

let completed = false;
var sub = (ko as any).bindingEvent.subscribe(node, 'childrenComplete', function () {
if (sub) {
    sub.dispose();
}
completed = true;
resolve();
}, null, { notifyImmediately: true });
if (completed) sub.dispose();

The error occurs on line 3442 of knockout-3.5.1.debug.js:

    ko.bindingEvent = {
        childrenComplete: "childrenComplete",
        descendantsComplete : "descendantsComplete",

        subscribe: function (node, event, callback, context, options) {
            var bindingInfo = ko.utils.domData.getOrSet(node, boundElementDomDataKey, {});
            if (!bindingInfo.eventSubscribable) {
                bindingInfo.eventSubscribable = new ko.subscribable;
            }
            if (options && options['notifyImmediately'] && bindingInfo.notifiedEvents[event]) { //Error because bindingInfo.notifiedEvents is undefined.
                ko.dependencyDetection.ignore(callback, context, [node]);
            }
            return bindingInfo.eventSubscribable.subscribe(callback, context, event);
        },

I changed the line as follows and no longer get an error:

if (options && options['notifyImmediately'] && bindingInfo.notifiedEvents && bindingInfo.notifiedEvents[event]) {

I believe that this API isn't supported externally, but I would still like it if this is fixed so I can use it regardless (understanding that it may not be supported in the future).