I'm new to knockout and trying to get my select2 to play nicely with my knockout bindings.
All I want to do is bind accounts array to my select2 (this works) and then
have the initial value set when the binding occurs. I for some reason can not get this to work. Also noticed that the init and update function get called initially, but anytime I change the value of the select2 dropdown, the update function is not being triggered.
Any help would be appreciated.
HTML
<div class="col-sm-12 col-md-3">
<fieldset class="form-group">
<label data-bind="attr:{for:'job'+laborDetailId()}">Job</label>
<select class="select2" data-bind="attr:{id:'job'+laborDetailId()},updateaccountdropdown: {value:account(),data:accounts,width:'100%'}">
</select>
</fieldset>
</div>
JS
var accounts = [{"id":-1,"text":"","description":null}, {"id":25,"text":"J13002","description":null}, {"id":28,"text":"J13053","description":null}];
var LaborListModel = function(laborModels) {
var self = this;
//contains all labor models
self.labordetails = ko.observableArray(laborModels);
self.selectedAccount = ko.observable();
//bindings
ko.bindingHandlers.updateaccountdropdown = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).select2('destroy');
});
var allBindings = allBindingsAccessor(),
select2 = ko.utils.unwrapObservable(allBindings.updateaccountdropdown);
$(element).select2(select2);
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var allBindings = allBindingsAccessor();
if ("value" in allBindings) {
var val = ko.utils.unwrapObservable(valueAccessor());
$(element).val(val.id).trigger('change');
}
}
};
}
getAllLaborDetails().done(function(result) {
loadAccounts().done(function(_accounts) {
accounts = _accounts;
for (var i = 0; i < result.length; i++) {
//LaborModel
var laborDetails = [];
laborDetails.push(new LaborModel(
result[i].labourDetailId,
result[i].account,
result[i].categoryModel,
result[i].description,
result[i].timeStamp,
result[i].hour
));
}
var vm = new LaborListModel(laborDetails);
ko.applyBindings(vm);
});
})
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…