I am trying to find out the best way of how to subscribe an custom jQuery event to a Knockout 3.2 view model.
I am using the FuelUX tree control and I would like to push the selected object to my view model observable whenever someone selects a tree item.
The FuelUx control has a built in jQuery event to handle the click and return to a function the selected jQuery data object that is attached to the DOM element. The following is basic code
$('#myTree').on('selected.fu.tree', function (evt, data) {
var selectedArray = $('#myTree').tree('selectedItems'); //fuelux custom event
ko.utils.arrayForEach(selectedArray, function (bnd) {
if (bnd) {
self.linked_documents.push(new DocFile(bnd.dataAttributes.document));
}
});
});
I have looked at the following and maybe this is the right approach. However any suggestions/recommendations would be appreciated.
http://knockoutjs.com/documentation/unobtrusive-event-handling.html
Thanks, Greg
Don't be fooled by the "event" term, the event
binding is mostly useful for binding to DOM events. Instead, you could use a custom binding handler to hook up a piece of the view to a UI plugin.
For example:
ko.bindingHandlers["fuelEX"] = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
$(element).on('selected.fu.tree', function (evt, data) {
// Modify your view model here in response to the plugin's event
var observable = valueAccessor();
observable(observable() + 1);
});
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Update the DOM element based on the supplied values here.
}
};
ko.applyBindings({
counter: ko.observable(1),
simulateFuelEXEvent: function() { console.log('hai'); $("#fuel").trigger("selected.fu.tree"); }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="fuel" data-bind="fuelEX: counter"></div>
<p>Counter value: <span data-bind="text: counter"></span></p>
<p><button data-bind="click: simulateFuelEXEvent">Simulate event</button></p>