ajax调用期间的KnockoutJS竞争条件

时间:2012-03-07 18:06:30

标签: javascript ajax knockout.js

这是一个奇怪的竞争条件发生在knockoutjs。我正在使用ajax调用独立设置两个observable。一个是列表,另一个是单个值。奇怪的是当我在列表之前加载单个值时,它将无法正确绑定。有什么建议吗?

JsFiddle:http://jsfiddle.net/JasonMore/bxfXd/110/

查看     

    <form data-bind='submit:addItem'>
        Add item: <input data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' type='text' />
        <button data-bind='enable: isAddButtonEnabled' type='submit'>Add</button>
    </form>

    <p>Your values:</p>
    <select data-bind='options:allItems, value:selectedItems' height='5'> </select>

    <div>
        <button data-bind='click: removeSelected'>Remove</button>
        <button data-bind='click: function() { allItems.sort() }, enable: allItems().length > 1'>Sort</button>
    </div>

</div>

代码

var betterListModel = function() {
    var self = this;

    // properties
    this.itemToAdd = new ko.observable("");
    this.allItems = new ko.observableArray();
    this.selectedItems = new ko.observable('');

    // computed
    this.isAddButtonEnabled = ko.computed(function() {
        return self.itemToAdd().length > 0
    });

    //methods
    this.addItem = function() {
        if ((this.itemToAdd() != "") && (this.allItems.indexOf(this.itemToAdd()) < 0)) this.allItems.push(this.itemToAdd());
        this.itemToAdd("");
    }

    this.removeSelected = function() {
        this.allItems.removeAll(this.selectedItems());
        this.selectedItems();
    } };

var view = new betterListModel();

ko.applyBindings(view);


// load $.ajax({
    url: '/echo/json/',
    type: 'post',
    data: {
        json: $.toJSON("Ham"),
        delay: 1
    },
    success: function(data) {
            view.selectedItems(data);
    } });

$.ajax({
    url: '/echo/json/',
    type: 'post',
    data: {
        json: $.toJSON(["Fries", "Eggs Benedict", "Ham", "Cheese"]),
        delay: 2
    },
    success: function(data) {
        $.each(data, function(index, value) {
            view.allItems.push(value);
        });
    } });

1 个答案:

答案 0 :(得分:0)

试试这个 - &gt; //每当状态改变时,重置selectedState选择

this.allItems.subscribe(function () {
this.selectedItems(arrayOfMySelectedItems);
});