Reputation: 801
I want to add some content to my page after data binding, e.g.:
$("<li>
<div>text</div>
<div data-bind='event: { click: selectContact }'></div>
</li>")
.appendTo($("#userClientGroup")
.find("#searched-client-ul-UCG"));
However, in this case the click event is not working; can any one can give me solution?
Upvotes: 2
Views: 2029
Reputation: 553
You can use ko.applybindings(viewModel, $('#yourNewElement'))
.Just be careful not to try binding an element already bound, or you'll have an error.
Upvotes: 5
Reputation: 3000
The best approach would be to avoid using jQuery (or any DOM method) to append new elements, in order to avoid having to bind your viewmodel against these elements. You can solve the problem either with existing bindings in your HTML or with a custom binding, or a combination. Your bindings should handle the DOM manipulation, not your other code (which shouldn't need to be aware of the DOM).
Another approach is to use a delegated event handler. I use the following custom binding:
ko.bindingHandlers.delegatedEvent = {
init: function (element, valueAccessor) {
var options = ko.unwrap(valueAccessor()) || {},
setupEventHandler = function (settings) {
if (settings.data) {
$(element).on(settings.event, settings.target, settings.data, settings.handler);
} else {
$(element).on(settings.event, settings.target, settings.handler);
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).off(settings.event, settings.target, settings.handler);
});
};
if ($.isArray(options)) {
$.each(options, function () {
setupEventHandler(this);
});
} else {
setupEventHandler(options);
}
}
};
Use this on the <ul>
you're inserting the li
into as such:
<ul data-bind="delegatedEvent: { event: click, target: '.contact-select', handler: selectContact }">
Add the class in your original insertion code, and remove the data-bind there.
$('<li><div>text</div><div class="contact-select"></div></li>')
.appendTo($("#userClientGroup").find("#searched-client-ul-UCG"));
Not only have you solved the problem, but you've replaced potentially lots of event handlers with just one.
Upvotes: 2