I am building a permissions UI, I have a list of permissions with a select list next to each permission. The permissions are represented by an observable array of objects which
Quick and dirty, utilizing a simple flag:
var bindingsApplied = false;
var ViewModel = function() {
// ...
this.permissionChanged = function() {
// ignore, if flag not set
if (!flag) return;
// ...
};
};
ko.applyBindings(new ViewModel());
bindingsApplied = true; // done with the initial population, set flag to true
If this doesn't work, try wrapping the last line in a setTimeout() - events are async, so maybe the last one is still pending when applyBindings() already returned.
Create js component
define([
'Magento_Ui/js/form/element/select',
'mage/translate'
], function (AbstractField, $t) {
'use strict';
return AbstractField.extend({
defaults: {
imports: {
update: 'checkout.steps.shipping-step.shippingAddress.shipping-address-fieldset.country_id:value'
},
modules: {
vat_id: '${ $.parentName }.vat_id'
}
},
/**
* Initializes UISelect component.
*
* @returns {UISelect} Chainable.
*/
initialize: function () {
this._super();
this.vat_id().visible(false);
return this;
},
update: function (value) {
if(value == 'GB'){
this.vat_id().visible(true);
}else{
this.vat_id().visible(false);
}
}
});
});
I had a similar problem and I just modified the event handler to check the type of the variable. The type is only set after the user selects a value, not when the page is first loaded.
self.permissionChanged = function (l) {
if (typeof l != 'undefined') {
...
}
}
This seems to work for me.
Actually you want to find whether the event is triggered by user or program , and its obvious that event will trigger while initialization.
The knockout approach of adding subscription
won't help in all cases, why because in most of the model will be implemented like this
(actual KO initilization)
(logical init like load JSON , get data etc)
The actual step that we want to capture is changes in 3, but in second step subscription
will get call ,
So a better way is to add to event change like
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
and detected the event in permissionChanged
function
this.permissionChanged = function (obj, event) {
if (event.originalEvent) { //user changed
} else { // program changed
}
}
If you use an observable instead of a primitive value, the select will not raise change events on initial binding. You can continue to bind to the change event, rather than subscribing directly to the observable.
use this:
this.permissionChanged = function (obj, event) {
if (event.type != "load") {
}
}