为什么我的Knockout绑定只能间歇性地工作?

时间:2014-05-27 12:07:32

标签: knockout.js

有些时候,我的可观察搜索条款'没有更新。它绑定到输入字段。如果我没有为valueUpdate使用特殊值,这似乎不会发生。

我的控制台没有错误。

<div data-bind="visible: true" style="display: none">

                <div class="search" style="clear:both;">
                    <input type="text" data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
                </div>

                <!-- ko if: filteredGames().length > 0 -->
                <div data-bind="foreach: filteredGames">
                    <a href="#" data-bind="click: $parent.loadGame">
                        <img data-bind="attr: {src: img}"/>
                        <span data-bind="text: name"></span>
                        <div class="play-game-btn">Play game</div>
                    </a>
                </div>
                <!-- /ko -->
                <!-- ko if: filteredGames().length == 0 -->
                    <p>No games found</p>
                <!-- /ko -->

            </div>

这是我的viewmodel代码:

window.games = [{"name": "name1", "url": "http://example.com", "width": 100, "height":100}]; // usually comes from the server

function GamesViewModel() {

    var self = this;

    this.games = window.games;
    this.noGames = ko.observable(false);
    this.searchTerm = ko.observable('');

    // this is to debug the binding itself. it logs something half the time.
    this.searchTerm.subscribe( function( x ) {
        console.log( x );
    });

    this.filteredGames = ko.computed( function() {
        var filter = self.searchTerm().toLowerCase();
        if (!filter) {
            return this.games;
        } else {
            return ko.utils.arrayFilter(self.games, function (item) {
                return item.name.toLowerCase().indexOf(filter) !== -1;
            }); 
        }
    });

    this.resetSearch = function() { this.searchTerm(null); };

    this.loadGame = function() {
        window.open( this.url, this.name, "width="+this.width+",height="+this.height );
    }
}

ko.applyBindings( new GamesViewModel() );

这里可能会发生什么?

更多细节

仅在软刷新(Cmd-R)后才会发生这种情况。进行硬刷新(Cmd-Shift-R)使其工作。

2 个答案:

答案 0 :(得分:0)

我在测试您的代码时在控制台中收到此错误:

  

未捕获错误:无法解析绑定。
  消息:TypeError:无法读取属性&#39; length&#39;未定义;
  绑定值:if:filteredGames()。length&gt; 0

当发生此错误时,&#34; searchTerm&#34;财产未更新。

尝试更改视图的此代码块:

<!-- ko if: filteredGames().length > 0 -->

对此:

<!-- ko if: filteredGames() && filteredGames().length == 0 -->

答案 1 :(得分:0)

这是由脚本冲突引起的。

相关问题