Take the 2-minute tour ×

I'm trying to modify an object on a click. Here's what I have.

    <ul class="tabs" data-tabs="tabs"  data-bind="template: 'lineTemplate'"></ul>

    <div class="pill-content" data-bind="template: 'lineDivTemplate'" ></div>

<script id="lineTemplate" type="text/html">
    {{each(i, line) lines()}}  
    <li><a data-bind="click: function() { viewModel.setActive(line) }, attr : { href : '#line' + id() }"><span style="font-size: 15px;" data-bind="text : model"/></a></li>

var viewModel = {       
    lines: ko.observableArray([]),
    setActive : function(line) {                
        **//I need to modify this object**

        line.activeTab = true;

$.getJSON("/json/all/lines", { customer_id : customer_id } , function(data) {       

    ko.mapping.fromJS(data, null, viewModel.lines);     


Basically when the user clicks the tab I need it to update the model(and eventually the database) that it is the currently active tab. The first way I had was the delete the object modify it and then push it back to the array, but pushing adds it to the end of the array, which I don't want. Thanks for any help.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Typically, you would mantain something like a "selectedTab" or "activeTab" observable.

var viewModel = {
  lines: ko.observableArray([]),
  activeTab: ko.observable(),

viewModel.setActive = function(line) {

Then, you can do any binding that you want against activeTab. In KO 1.3, you could do:

<div data-bind="with: activeTab">
  ...add some bindings here

Prior to that you could do:

<script id="activeTmpl">
   ...add your bindings here
share|improve this answer
This works good but I'm looking for something much simpler. All I want to do is modify a property within an observableArray. This makes it easier when I'm writing the information to the database if I have the property already in the object. The way you have it I would have to serialize a totally different object, get the id then pass it as a separate POST and update it. Thanks. –  Drew H Nov 7 '11 at 21:36
The activeTab in this case is just a reference to the same line object from the observableArray. So, it would not be a totally different object. –  RP Niemeyer Nov 7 '11 at 22:21
add comment

Your Answer


