Stranger
Stranger

Reputation: 862

Knock Out data binding

I have a question about data binding using knockout.

Here's the problem: I have a table, I what I would like to do is that when a row in table is clicked, I want the values of the row to appear in the input fileds which are located above the table.

so here'

<tbody data-bind="foreach: customers">
                        <tr data-bind="click: doSomething">     
                            <td data-bind="text: date"></td>
                            <td data-bind="text:staff"></td>
                            <td data-bind="text: ftype"></td>
                            <td data-bind="text: value"></td>
                            <td data-bind="text: message"></td>
                            </td>
                        </tr>
                    </tbody>

In my viewmodel, I have the following function:

doSomething: function(data) { 
        var self = this;      
        self.date(data.date);        
        self.staff(data.staff); 
        self.ftype(data.ftype);
                   self.value(data.value);
                   self.message(data.message);  

    }

Here's the error I am getting:

["Unable to parse bindings.↵Message: ReferenceError:… is not defined;↵Bindings value: click: doSomething", "views/myView/index", Object]
   0: "Unable to parse bindings.↵Message: ReferenceError: doSomething is not          defined;↵Bindings value: click: doSomething"
 1: "views/myView/index"
  2: Object
length: 3
 __proto__: Array[0]

Let me know if I need to provide any more details. I will appreciate your help fplks!

Upvotes: 0

Views: 108

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

A very basic pattern for this type of thing is to have an array of items and a selectedItem observable that you populate when selecting a row.

Then, you can use the with binding around a section to create your editor.

<table>
    <tbody data-bind="foreach: customers">
        <tr data-bind="click: $root.selectedCustomer">     
            <td data-bind="text: name"></td>
        </tr>
    </tbody>
</table>

<hr/>

<div data-bind="with: selectedCustomer">
    <input data-bind="value: name" />
</div>

Sample: http://jsfiddle.net/rniemeyer/Z6VPV/

Upvotes: 1

Darussian
Darussian

Reputation: 1593

You need to bind your model to the view

 var currentViewModel = function(){
   this.doSomething = function(data){
      var self = this;      
      self.date(data.date);        
      self.staff(data.staff); 
      self.ftype(data.ftype);
                 self.value(data.value);
                 self.message(data.message);  
  }
var viewModel = new currentViewModel();
ko.applyBindings(viewModel);

Upvotes: 0

Related Questions