Reputation: 7384
I have a viewmodel, that has a callback as a parameter to the constructor - call it "onReady", along with other necessary parameters. It cannot be bound to the view (template) until the callback has executed. Is there any way this can work with knockout components? It seems knockout components try to avoid this as "createViewModel" needs to be synchronous.
Upvotes: 0
Views: 1113
Reputation: 1459
The async work can be done by the viewmodel or the script file, find attached a sample.
// ViewModel object
// Really? callback as a constructor parameter?
function ViewModel(callback){
// busy message
this.message=ko.observable("loading");
var _this=this;
callback(function(response){
_this.message(response);
});
}
// register the component
ko.components.register('onready', {
viewModel: function(params) {
return params.viewModel
},
template:
'<div data-bind="text:message"></div>'
});
// make viewmodel instance
var viewModel=new ViewModel( function(response){
// start the async work
window.setTimeout( function(){
response("ready!");
},1000);
}
);
// plain normal ko
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<onready params="viewModel:$data"></onready>
Upvotes: 1