使用knockout js在UI中对象值不会改变

时间:2014-04-08 09:30:34

标签: knockout.js knockout-2.0 knockout-mapping-plugin

我使用jquery移动列表来表示UI中的数据,当用户点击该元素时,它会转到该记录的详细信息页面,

Page stateManage js

PageStateManager = (function () {
    var viewModels = {};

    var changePage = function (url, viewModel) {
        alert(">>>>>>>> "+ viewModel.runticketNumber());
        $.mobile.changePage(url, {viewModel: viewModel});
    };

    var registerViewModel = function (viewModelName, viewModel) {
        viewModels[viewModelName] = viewModel;
    };

    var initPage = function(page, newViewModel) {
        var viewModelName = page.attr("data-viewmodel");

        if (viewModelName) {
            if (newViewModel) {
                registerViewModel(viewModelName, newViewModel);
            }

            // get view model object
            var viewModel = viewModels[viewModelName];

            // apply bindings if they are not yet applied
            if (!ko.dataFor(page[0])) {
                ko.applyBindings(viewModel, page[0]);
                viewModel.errors = ko.validation.group(viewModel);
                ko.validation.group(viewModel).showAllMessages(false);
            }
        }
    };

    var onPageChange = function (e, info) {
        initPage(info.toPage, info.options.viewModel);
    };

    $(document).bind("pagechange", onPageChange);

    return {
        changePage: changePage,
        initPage: initPage
    };
})();

Ticket js

function RunTicket(jsRunTicket) {
    var self = this;
    ko.mapping.fromJS(jsRunTicket, {}, this);    
    self.save = function(){
          alert(">>>> " +this.isValid());
    }

列表视图html

<div id="listViewDiv">
            <ul data-role="listview">
                <!-- ko foreach: tickets -->
                <li data-bind="click:$root.clickList">
                    <h2>Ticket No:<span data-bind="text:action"></span></h2>
                    <p>Item <span data-bind="text:deliveryNetworkName"></span></p>
                    <p class="ui-li-aside"><strong><span data-bind="text: runTicketType"></span></strong></p>
                </li>
                <!-- /ko -->
            </ul>
        </div>
}

查看模型

   var viewModel = {
         clickList : function(val){
            var rt = new RunTicket(service.getRunTicket(val.id));
            PageStateManager.changePage($("#detailsView"),rt);
        }
        seats :[{"action":"SAVE","bsW":null,"date":"2013-12-19T17:11:00","deliveryNetworkName":"XXXXX 7-2932H","runticketNumber":3957,"id":75837},{"action":"SAVE","bsW":null,"date":"2013-12-19T17:11:00","deliveryNetworkName":"XXXXX 7-2932H","runticketNumber":3958,"id":75837}] 
    }
applyBindings(viewModel,document.getElementById("firstPage"))

根据用户选择不改变的记录,只包含用户从列表中选择的第一个值,任何人都可以帮我找到问题

1 个答案:

答案 0 :(得分:2)

问题是您在ko.applyBindings中呼叫PageManager时绑定到视图模型。在此之后,视图模型将永远不会改变。您应该将当前选定的医院放入视图模型的可观察属性中,并在页面更改事件上设置该可观察属性值。

我已将您的jsfiddle更新为可在以下位置找到的工作样本:http://jsfiddle.net/Hpyca/13/