Domanda

i am having some issue translating/replacing the value of data-bind with ko.mapping, here is what i have tried so far

my View

<span data-bind="translate: address.place"></span>

NOTE:address.place will be set by ko.mapping from server

my viewModel

   ko.bindingHandlers.translate = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            console.log(viewModel.address.city);// how i can get the cityName

            if (viewModel.address.street._latestValue == "koeln") {
                //set back city to  cologne
            }

        },
        update: function (element, valueAccessor) {
            ////

        }
    };
È stato utile?

Soluzione

This doesn't really have anything to do with the KO mapping plugin. Assuming you are correctly getting the initial data into your viewmodel (whether you are using the mapping plugin or not), all your binding handler is doing is changing what is displayed in the UI.

You can access other members of your view model through the a parameter in your binding handler commonly named as bindingContext. See this section of the KO docs for more info.

So you could rewrite your binding handler like so:

  ko.bindingHandlers.translate = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            console.log(bindingContext.$data.address.city());// the cityName

            if (bindingContext.$data.address.street._latestValue == "koeln") {
                //set back city to  cologne
                bindingContext.$data.address.city('cologne');
            }

        },
         /// add your update section if needed
    };
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top