0

基本的に、私が達成しようとしているのは、Knockout.jsの別のドロップダウンの値に基づいてドロップダウンを設定することです

私のビューコード(明らかに削除されました):

            <div data-bind="with: chosenMailData">
                <table id="tabl-1234" class="mails">
                    <thead><tr><th>Destination</th><th>Hotel</th></tr></thead>
                    <tbody data-bind="template: { name: 'iti-template', foreach: objects, afterRender: $root.myPostProcessingLogic }">
                </table>
            </div>

            <script type="text/html" id="iti-template">
                <tr>
                    <td><select class="desti" data-bind="options: $root.destinations, value: destination.name"></select></td>   
                    <td><select data-bind="options: $root.generall(), value: $root.generall()"></select></td>
                </tr>
            </script>

私の見解-モデル(ここでも削除):

            self.destinations=['Kerela', 'Shoghi, Himachal Pradesh', 'Kasauli, Himachal Pradesh'];

            self.myPostProcessingLogic = function(elements) {
                this.generall = ko.computed(function() {
                    $('.desti').each(function(i, obj) {
                        stayOptions = [];
                            $.getJSON("http://127.0.0.1:8000/api/hotel?format=json&location__name="+obj.value, function(data) {
                                    $.each(data.objects, function(i, item){
                                    stayOptions.push(item.name);
                                    });
                                });
                    });
                    return stayOptions;
                }, this);
            }

ショーに挿入alert()すると、必要な値が入力されます。問題となっているHotels列の対応する行の選択オプションにその配列が表示されるようになっています。this.generall()stayOptions

おそらく私は本当にばかげた間違いを犯していますが、私は長い間コードを見ていて、何も思い浮かびません。お知らせ下さい。

編集:ビューモデルの最初にこれも行っています:

            self.generall = ko.observableArray();
4

1 に答える 1

2

メソッドを呼び出すと、呼び出し時にthis変数が割り当てられます。

var f = $root.myPostProcessingLogic;
f(); // this will not set 'this' to '$root'

上記は本質的にノックアウトが行っていることであり、これにより、this内部の別の何かにバインドされますmyPostProcessingLogic()。スコープ変数は既に定義されているselfため、これは簡単に修正できます。

もう 1 つの問題は、オブザーバブルを再割り当てしてもサブスクライバーが保持されず、依存するオブザーバブルが更新されないことです。

self.generall = ko.observableArray();
self.myPostProcessingLogic = function(elements) {
    self.generall.removeAll();
    $('.desti').each(function(i, obj) {
        $.getJSON("http://127.0.0.1:8000/api/hotel?format=json&location__name="+obj.value, function(data) {
            $.each(data.objects, function(i, item){
                self.generall.push(item.name);
            });
        });
    });
}
于 2012-12-20T08:27:31.207 に答える