Skip to content

Instantly share code, notes, and snippets.

@deanstalker
Created April 24, 2015 05:52
Show Gist options
  • Save deanstalker/0dbc21f915d7fca4829f to your computer and use it in GitHub Desktop.
Save deanstalker/0dbc21f915d7fca4829f to your computer and use it in GitHub Desktop.
var Example = Example || {};
Example = (function() {
var component = function() {
ko.components.register('test',{
viewModel: function(params) {
var self = this;
self.init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
setTimeout(function() {
// Anything in here will be executed once the component is ready.
}, 100);
};
self.update = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// without the set timeout, the component / dom won't be ready in time, and the dom events will be ignored.
};
},
template: '<select class="select2" data-bind="selectTest: {}"></select2>'
})
},
bindingHandler = function() {
ko.bindingHandlers.selectTest = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// The dom events may be initialised by this point, however the component generated DOM elements will not be ready.
if (bindingContext.$data.init) { bindingContext.$data.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// The dom events may be initialised by this point, however the component generated DOM elements will not be ready.
if (bindingContext.$data.update) { bindingContext.$data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
}
};
}
return {
init: function() {
component();
bindingHandler();
}
}
})(ko);
Example.init();
<div>
<!--ko component: { name: 'test', params: {} }--><!--/ko-->
</div>
<script type="text/javascript">
var ExampleModel = {};
ko.applyBindings(ExampleModel);
</script>
@deanstalker
Copy link
Author

Components do not have an afterRender callback, so the only way to trigger it is with a binding handler added to the containing element - any DOM calls need to be wrapped in a setTimeout of at least 50-100ms to allow time for the DOM to reach ready state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment