开发者

Why doesn't my knockoutjs observableArray data update trigger anything?

The idea of this page is, I have a text field which, when you enter three or more characters, fires an ajax query to search the list of users. That part works fine, and the console.log() call demonstrates I'm getting good data back and assigning it to the .users field of my view model.

The problem is, that doesn't trigger any of the observable behavior. Up in the HTML I have a template that is bound with foreach: users, and I have a span bound on userCount, neither of which update. However, if I type viewModel.users().length on the console, I get the right value. But I've somehow broken observability.

var viewModel = {
    users: ko.observableArray([]),
    term: ko.observable('')
};


ko.dependentObservable( function() {
    if (this.term().length > 2) {
        $.get('http://mydatasource.com/path/?term=' + this.term(),
        function(data) {
            viewMo开发者_StackOverflowdel.users(data);
            console.log(viewModel.users());
        })
    }

}, viewModel);

viewModel.userCount = ko.dependentObservable( function() {
    return this.users().length;
}, viewModel );


ko.applyBindings(viewModel);

EDIT: Just modified my ajax getting dependentobservable function to:

ko.dependentObservable( function() {
    if (this.term().length > 2) {
        $.get('http://mydatasource.com/path/?term=' + this.term(),
        function(data) {
            viewModel.users([]);
            $.each(data, function(i, item) {

                console.log(item.label);
                viewModel.users.push({value: ko.observable(item.value), label: ko.observable(item.label)});

            } );
        })
    }

}, viewModel);

No difference at all. But I can see the properly-returned label values in the console, and again, viewModel.users().length gives me answers I'm happy with.

EDIT: I replaced my view with the one @RP Niemeyer provided in a fiddle, and it worked... SO it's something about my view. Here's what I had:

<input data-bind="value: term, valueUpdate: 'afterkeydown'"><br/>
<h2><span data-bind="value: userCount"></span> Users Listed</h2>
<table data-bind="foreach: users">
    <tr><td data-bind="text: label"></td><td data-bind="text:value"></td></tr>
</table>

<div data-bind="text: ko.toJSON(viewModel)"></div>


Looks fine from the code you posted. Maybe post some of your view or try to repro based on this fiddle: http://jsfiddle.net/rniemeyer/FDZJx

Update: used your view: http://jsfiddle.net/rniemeyer/FDZJx/2/. Still looks fine. Your first input element was not closed, but it didn't cause me a problem. Possibly causes a problem in the browser that you are using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜