Binding multiple view models on single tag

时间:2015-09-01 22:47:35

标签: knockout.js

I have the following select tag:

<select data-bind="value: schedule_id, options: courses, optionsText: 'title', optionsValue: 'schedule_id'"></select>

I have 2 view models. One manages courses and the other manages reviews.

The problem I'm facing is that the select needs to get its values from the courseViewModel and my reviewViewModel needs to observe what value is selected so it knows what course is being reviewed.

So I need to bind options: courses, optionsText: 'title', optionsValue: 'schedule_id' to my courseViewModel and bind value: schedule_id to my reviewViewModel so it knows what course was selected to review.

When I apply the bindings for the courseViewModel, I get an error saying no binding exists for value: schedule_id.

How do I solve this?

1 个答案:

答案 0 :(得分:1)

You solve that by defining a proper view model.

The idea in a view model is that it contains all the data required by the view to generate the representation of that data.

You can:

  1. Combine both view models
  2. Define a 3rd view model that has the relevant data parts
  3. As an "advanced" technique, you could generate a property(s) on one of the models that actually access values from the 2nd model. use Object.defineProperty to define a getter for values that don't "exist" in the view model itself, but a rather pulled from the other view model.