Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout Js - Binding a single item from a json array to an element

I have the following view model which contains an array of elements

   function ReservationsViewModel() {
        var self = this;


        self.availableMeals = [
            { mealName: "Standard (sandwich)", price: 0, id = 1 },
            { mealName: "Premium (lobster)", price: 34.95, id = 2 },
            { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
        ];  
  }

I want to bind this view model to a input, but i want to bind only the Single array element meal name that has the id value as the data-id attribute of the input.

<input type="text" id="firstElementMealName" data-id="1" data-bind="value: ??"></input>

In this example i would bind the array element with id = 1, and the text would appear as "Standard (Sandwich)", but i still need the full binding and change tracking (observables) and all the other good stuff in Knockout.

How to pick up the data-id and use it in the binding code to bind the appropriate meal to the input?

Thanks in advance

like image 476
Faris Zacina Avatar asked Feb 01 '12 23:02

Faris Zacina


1 Answers

Suggested solution:

   function ReservationsViewModel() {
        var self = this;


        self.availableMeals = ko.observableArray([
            { mealName: "Standard (sandwich)", price: 0, id = 1 },
            { mealName: "Premium (lobster)", price: 34.95, id = 2 },
            { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
        ]);

        self.getMealById = function(id) {
            ko.utils.filterArray(self.availableMeals(), function(item) {
                return item.id == id;
            });
        };
  }

In the view:

<input type="text" id="firstElementMealName" data-bind="value: getMealById(1)"></input>

EDIT: here is a two-way solution:

function ReservationsViewModel() {
        var self = this;


    self.availableMeals = ko.observable({            
        id_1: { mealName: "Standard (sandwich)", price: ko.observable(0) },
        id_2: { mealName: "Premium (lobster)", price: ko.observable(34.95) },
        id_3: { mealName: "Ultimate (whole zebra)", price: ko.observable(290) }
        });
  }

ko.applyBindings(new ReservationsViewModel());

In the View:

<input type="text" id="firstElementMealName" data-bind="value: availableMeals().id_2.price()"></input>
like image 183
Andreas Helgegren Avatar answered Oct 25 '22 15:10

Andreas Helgegren