これがjsFiddleの例です
私は jsFiddle を一緒に投げて、私が達成しようとしていることを実証しようとしました (これまでの 3 回目の試行を反映しています)。
KnockoutJSをいじり始めたばかりで、少し困惑しています。これが私がやりたいことです。
JSON 文字列を返す asmx メソッドがあります。これは、次のオブジェクトが逆シリアル化されたものです (簡潔にするために、ほとんどのプロパティは省略されています)。
class Template
{
public int Id { get; set; }
public string Name { get; set; }
public List<Group> Groups { get; set; }
}
class Group
{
public string Name { get; set; }
public List<Question> Questions { get; set; }
}
class Question
{
public string Text { get; set; }
}
ユーザーselect
がTemplate
. 1 つを選択すると、オフになり、上記のメソッドを呼び出してそのテンプレートの構成を返します。
最初に、これらのテンプレートのリストを使用して、次のように JavaScript ビュー モデルを作成しています。
function viewModel(templates) {
var self = this;
self.templates = ko.observableArray(templates);
}
// this is just a $.ajax call to another asmx service that gets me
// a JSON array of all templates
var templates = getTemplates();
var vm = ko.applyBindings(new viewModel(templates));
次に、私のマークアップはこれを次のように使用します。
<select id="template" data-bind="foreach: templates">
<option data-bind="text: Name, value: Id"></option>
</select>
私の質問は、テンプレートの構成を返し、これをビューモデルに保存し、ページに表示する正しい方法は何だと思いますか?
最初の試み
ビュー モデルにプロパティconfiguration
とメソッドを追加し、.getConfiguration
data-bind="change: getConfiguration
select
function viewModel(templates) {
var self = this;
self.templates = ko.observableArray(templates);
self.configuration = null;
self.getConfiguration = function () {
// calls the asmx web method, parses the returned JSON to an object
// and then...
self.configuration = $.parseJSON(data.d);
};
}
しかし、私はあまり運が良くありません.誰かが私に正しい方向への親切なナッジを与えることができますか? いつものようにすべての助けに感謝します。
2 回目の試行
以下のマエルの回答に基づいてconfiguration
、オブザーバブルとして設定しようとしました。これが私のマークアップです(現時点ではテンプレートの名前を観察しようとしています):
<div data-bind="if: configuration">
<strong data-bind="text: configuration.Name"></strong>
</div>
そしてgetConfiguration
方法:
var config = $.parseJSON(data.d); // the ajax call to get the JSON
self.configuration = ko.observable(config);
また、マッピングプラグインでこれを試しました:
self.configuration = ko.mapping.fromJS(config);
でも運がない:s
3 回目の試行
テンプレート リストをビュー モデルに格納するという考えを破棄することに決め、このリストを個別に作成しています。がテンプレート リストのイベントで呼び出さko.applyBindings
れるようになりました。.change
var viewModel = function (config) {
var self = this;
self.configuration = config;
}
$('#templates').unbind('change').on('change', function () {
var id = $(this).children('option:selected').val();
var config = getConfig(id); // calls my asmx method to get the config JSON
ko.applyBindings(new viewModel(config));
});
これではるかに成功しました(ビューモデルからテンプレートリストを削除する必要があるかどうかはわかりませんが)-しかし、次のエラーが表示されます[バインディングを同じ要素に複数回適用することはできません.].