Knockout.js: conditionally bind title attribute of div
Asked Answered
W

2

9

I have a viewModel on my page that holds the data for an overview of current states of some devices. So far everything works great except for one issue: I need to set the title attribute of a div element depending on another value in my viewModel.

I know that you can basically set the title attribute like this (within the data-bind attribute of the div tag):

attr: { title: 'Some title' }

Using the statement above, "Some title" gets set as tooltip when hovering the div. I can also set this:

attr: { title: ConnectState.Value() }

and it outputs the correct value (an integer value) of my current viewModel data, so the viewModel gets populated correctly.

Now I need to change this to something like that:

attr: {
  title: {
    'Text 1': ConnectState.Value() == 0,
    'Text 2': ConnectState.Value() == 1,
    'Text 3': ConnectState.Value() == 2,
    'Text 4': ConnectState.Value() == 3
  }
}

The example above will only give "[object Object]" as title (resp. as tooltip). How can I fix that? Thanks a lot in advance!

Wakeful answered 18/6, 2013 at 14:0 Comment(2)
Why don't you write attr: { title: 'Text ' + (ConnectState.Value() + 1) } Or your actual text is more complicated than your example?Holster
Unfortunately, it is. The value of ConnectState is an enum that translates into "connected", "disconnected", "connecting" etc.Wakeful
S
11

Define a ko.computed in your viewmodel.

self.ConnectTitle = ko.computed(function() {
   return 'Text ' + (self.ConnectState.Value() + 1).toString();
});

Then:-

attr: { title: ConnectTitle }

As your binding. You can replace the contents of the computed's function with something that'll suit your needs, if your text was just a simple example.

Sumerlin answered 18/6, 2013 at 14:7 Comment(2)
Thanks for your suggestion. The title attribute I need to set exists in a data-bound table row: <tbody data-bind="foreach: Rows"> So I have to apply this ConnectTitle function to every item in my viewModels "Rows" collection, which is dynamically, depending on the page. I couldn't figure out how to achieve that.Wakeful
Each of your rows is represented by an object, correct? Post your Javascript view model and we'll take a look.Sumerlin
S
4

You can use ternary operator, something like this:

attr: { 
  title: ConnectState.Value() == 0 ? 'Text 1' :
         ConnectState.Value() == 1 ? 'Text 2' :
         ConnectState.Value() == 2 ? 'Text 3' :
         'Text 4'
}
Starve answered 11/3, 2015 at 20:26 Comment(1)
That's elegant! Never used a ternary like this.Wakeful

© 2022 - 2024 — McMap. All rights reserved.