9

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

1 Answer 1

16

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>
Sign up to request clarification or add additional context in comments.

3 Comments

It works in one direction, but i still don't get the two-way binding. i would like the price to display in the input, and then when i change it i would like the binding to update it automatically in the viewmodel?
Looks like the getMealById function is missing a closing ')'?
Thanx! Have fixed it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.