0

I don't know why my currentTitle is not changing on click.

viewModel = {
    articles: ko.observableArray([{
        id: 1,
        title: "Article One",
        content: "Content for article one."},
    {
        id: 2,
        title: "Article Two",
        content: "Content for article two."},
    {
        id: 3,
        title: "Article Three",
        content: "Content for article three."}
                                               ]),
    currentTitle: ko.observable("old")
};


<div data-bind="foreach: viewModel.articles()">
<div data-bind="text:title,click: getTitle"></div>
</div>
<div data-bind="text: viewModel.currentTitle"></div>


getTitle = function(){
        viewModel.currentTitle = "title";
}
ko.applyBindings(viewModel);

Posted my code here : http://jsfiddle.net/devnegikec/TBP43/

Devnegikec
  • 631
  • 5
  • 11
  • possible duplicate of [Setting value of Observable not updating in Knockout](http://stackoverflow.com/questions/19391415/setting-value-of-observable-not-updating-in-knockout) – nemesv Apr 22 '14 at 09:04
  • Please mark an answer as accepted if you are happy with it and it adequately answers your question. – phuzi Apr 30 '14 at 11:45

3 Answers3

1

Your getTitle function updates the value of currentTitle rather than updating the observable.

Try:

getTitle = function(){
    viewModel.currentTitle("title");
}
phuzi
  • 12,078
  • 3
  • 26
  • 50
0

As @phuzi said, you're not updating the observable correctly, but you also need to pass the selected item to the function too:

getTitle = function(item){
    viewModel.currentTitle(item.title);
}

See here: updated fiddle

Tanner
  • 22,205
  • 9
  • 65
  • 83
0

http://jsfiddle.net/TBP43/3/

Changed: getTitle to setTitle.

Included setTitle in viewmodel.

Removed unnecessary 'viewmodel.' in binding.

I would recommend having a 'chosenArticle' in the viewmodel and simply binding the text with

   text: chosenArticle.title

PS: Please remove the jquery tag

Rune Jeppesen
  • 1,121
  • 13
  • 22