问题
The following binding worked prior to 1.9:
ko.bindingHandlers.accordion = {
init: function(element, valueAccessor) {
var options = valueAccessor() || {};
setTimeout(function() {
$(element).accordion(options);
}, 0);
ko.utils.domNodeDisposal.addDisposeCallback(element, function(){
$(element).accordion("destroy");
});
},
update: function(element, valueAccessor) {
var options = valueAccessor() || {};
$(element).accordion("destroy").accordion(options);
}
}
But since 1.9, it no longer works, and the following error is given:
Uncaught Error: cannot call methods on accordion prior to initialization; attempted to call method 'destroy'
I'm having trouble figuring out why. I looked over the jQuery UI upgrade notes, but nothing seemed relevant.
What's causing this, and what about my binding needs to change?
回答1:
Uncaught Error: cannot call methods on accordion prior to initialization; attempted to call method 'destroy'
This error says that you are calling destroy
method of accordion widget before initializing the widget.
The issue is with your custom binding code where you use setTimeOut
. The code inside setTimeOut runs after your update function. So the accordion plugin is not initialized over your element and in your update function you are calling destroy
method of the accordion.
A simple alternative is you should check whether accordion plugin is initialized over the element or not before calling any method, like :
if(typeof $(element).data("ui-accordion") != "undefined"){
$(element).accordion("destroy").accordion(options);
}
Here you can check Working jsbin.
来源:https://stackoverflow.com/questions/15673040/knockout-accordion-bindings-break