0

In knockout.js we have a basic example with the most basic text binding:

Today's message is: <span data-bind="text: myMessage"></span>

<script type="text/javascript">
    var viewModel = {
        myMessage: ko.observable() // Initially blank
    };
    viewModel.myMessage("Hello, world!"); // Text appears
</script>

This is straight from tutorial http://knockoutjs.com/documentation/text-binding.html What if I want to have a variable that defines the actual binding property. That could look something like this:

Today's message is: <span data-bind="myBinding: myMessage"></span>

<script type="text/javascript">
    var viewModel = {
        myMessage: ko.observable(), // Initially blank
        myBinding: ko.observable(), // Initially blank
    };
    viewModel.myMessage("text");
    viewModel.myMessage("Hello, world!"); // Text appears
</script>

Above code is obviously wrong, but what would the correct case be?

I was looking into some stuff like ko.applyBindingsToNode ( Can I dynamically bind element inside custom binding? ) but the Google FU is totally failing me this time, because most of the thing I find is applying bindings to dynamically built elements and not apllying dynamic binding types dynamically.

Community
  • 1
  • 1
povilasp
  • 2,386
  • 1
  • 22
  • 36

1 Answers1

1

You cannot use an observable as a custom binding type. Observable's are for storing data.

You can get the functionality you want by using either a Custom Binding or a Computed Observables. Personally, if this is something special that you need one time, then use a Computed Observable. Otherwise, use a custom binding.

photo_tom
  • 7,292
  • 14
  • 68
  • 116