Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js: conditionally bind title attribute of div

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!

like image 569
Rob Avatar asked Jun 18 '13 14:06

Rob


1 Answers

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.

like image 155
Paul Alan Taylor Avatar answered Oct 07 '22 17:10

Paul Alan Taylor