How do I get data out of a custom function inside a custom binding handler into the viewmodel?

StackOverflow https://stackoverflow.com/questions/18750996

  •  28-06-2022
  •  | 
  •  

質問

I have a 3rd party control that is initialized in my view:

<!--<ul data-bind="template: { name: 'itemTmpl', foreach: treeGroups }, groupTree: {}"></ul>/-->

with a custom binding handler:

ko.bindingHandlers.groupTree = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var tm = valueAccessor();
        var tmUnwrapped = tm();
        $(element).fancytree({
            minExpandLevel: 1,
            source: tmUnwrapped,
            lazyload: function (e, data) {
                data.result = datacontext.getGroupChildren('1111');
            },
            activate: function (event, data) {
                //logEvent(event, data);
                var node = data.node;
                // access node attributes
                alert(node.title);
            },

        })
    },

and all I'd like to be able to do is get the value I'm currently "alerting" in the "activate" method (node.title) into an observable in my viewmodel. As the event is triggered sort of "inside" the treeview and handled by the activate method I can't see how I can get the node.title into an observable which is buried in the root viewmodel ($root.selectedTitle).

役に立ちましたか?

解決 2

As the custom binding automatically inherits the bindingcontext from the view its contained within, all that was needed was to access the $root model from the bindingcontext in the custom binding handler:

ko.bindingHandlers.groupTree = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var rootVm = bindingContext.$root;
    $(element).fancytree({
        minExpandLevel: 1,
        source: tmUnwrapped,
        lazyload: function (e, data) {
            data.result = datacontext.getGroupChildren('1111');
        },
        activate: function (event, data) {
            var node = data.node;
            rootVm.selectedArticle(node.title);
        },
    })
}

他のヒント

$root or $parent psuedo variables are only available from within the context of data-binding. However, you could pass those values into your custom binding with something like this:

//in your view
data-bind="groupTree: {rootVm: $root}"

//in your binding
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    var settings = valueAccessor();
    var rootVm = settings.rootVm;
    //...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top