Pregunta

How do I create a global binding in knockout?

I want to be able to do something like this:

<div class="col-lg-6" data-bind="visible: IsPayingUser">
    <!-- the server will not send any data for freemium, 
         so hide the element unless it's a paying customer -->
</div>

That is, I do not want to create IsPayingUser as a property in every view model, but define it one time only.

¿Fue útil?

Solución

You can instruct Knockout to explicitly 'escape' the View-Model scope by using the window keyword:

<div class="col-lg-6" data-bind="visible: window.UserData.IsPayingUser">

And in your JavaScript:

window.UserData = { IsPayingUser = ko.observable(false) };

It's worth noting though that the 'Knockout way' to do it is to use nested View-Models and try to avoid pollution of the global scope.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top