I am using knockout with ASP.NET MVC for some project.
I am using the following bindingHandler
of knockout
ko.bindingHandlers.select2 = {
after: ["options", "value", "selectedOptions"],
init: function (el, valueAccessor, allBindingsAccessor, viewModel) {
// no explicit reference to the 'after' variable
},
update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
// no explicit reference to the 'after' variable
}
}
I got this code from this question and I modified it little.
It is basically a custom binding handler
for the Select2 plugin.
Question
I just want to know what the after: ["options", "value", "selectedOptions"],
means here. There is no reference to this variable anywhere in the init
or update
functions.
Does this variable have any meaning in this context? or is this an instruction to knockout to make it execute this custom binding after finish executing [options
, value
, selectedOptions
] bindings?
Note the documentation of the custom binding mentions nothing about this variable.
You're right in that it appears to be undocumented. Digging into the KO source code shows us this:
// First add dependencies (if any) of the current binding
if (binding['after']) {
cyclicDependencyStack.push(bindingKey);
ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
if (bindings[bindingDependencyKey]) {
if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
} else {
pushBinding(bindingDependencyKey);
}
}
});
cyclicDependencyStack.length--;
}
Your assumption appears to be correct. KO is building a list of dependent bindings that must run before the current binding can run. The built-in value and selectedOptions bindings take advantage of this keyword.
Here is the discussion on implementation from the Knockout Github
Here is a related StackOverflow answer
See the JSFiddle in that answer for example code.