【问题标题】:How to use the mapping plugin for knockout?如何使用映射插件进行淘汰赛?
【发布时间】:2012-04-13 09:57:55
【问题描述】:

我写了以下代码

$(function() {



    function get_updates () {
        $.getJSON('/new-lines.json', function(data) {
            var fullViewModel= ko.mapping.fromJS(data);
            ko.applyBindings(fullViewModel)


        });
    }

    function poll()
    {
        setTimeout(function(){
        get_updates();
        poll();},3000)

    }




    poll()
});

JSON 数据如下所示:

{"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"}

html 部分应该怎么写?

我对 javascript 很陌生。请帮忙。

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    您的问题有点误导,因为您似乎正确使用了映射插件。

    不正确的是您使用淘汰赛的方式。您每 3 秒轮询一次,加载数据然后重新绑定。对于典型的 KO 应用程序,建议您只调用一次applyBindings

    如果您定期更新模型,那么您使用映射插件的方法是正确的。这是我的做法。

    http://jsfiddle.net/madcapnmckay/NCn8c/

    $(function() {
        var fakeGetJSON = function () {
            return {"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"};
        };
    
        var viewModel = function (config) {
            var self = this;
    
            // initial call to mapping to create the object properties
            ko.mapping.fromJS(config, {}, self);
    
            this.get_updates = function () {
                ko.mapping.fromJS(fakeGetJSON(), {}, self);
            };            
        };
    
        // create viewmodel with default structure so the properties are created by
        // the mapping plugin
        var vm = new viewModel({ state: "M", qualities: [], name: "Foo" });
    
        function poll()
        {
            setTimeout(function(){
                vm.get_updates();
                poll();
            }, 3000)
        }
    
        // only one call to applybindings        
        ko.applyBindings(vm);
        poll();
    });
    

    还有一个示例html

    <h1>Name <span data-bind="text: name"></span></h1>
    <h2>State <span data-bind="text: state"></span></h2>
    <ul data-bind="foreach: qualities">
        <li data-bind="text: $data"></li>
    </ul>
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢。我还有一个疑问。如何映射作为我上面提到的对象数组的 JSON。例如:[{"state": "R", "qualities": ["ABC", "XYZ", "324"], "name": "ABC"},{"state": "E", "qualities": ["ABCD", "XYZW", "304"], "name": "ABe"}]
    • 这是实际运行的更新后的 jsFiddle。 (更新了已更改的 JS 资源 URL)jsfiddle.net/NCn8c/51
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多