使用knockout映射插件将深层分层对象映射到自定义类

发布于 2024-12-06 06:19:54 字数 1257 浏览 0 评论 0原文

使用剔除映射插件 ( http://knockoutjs.com/documentation/plugins-mapping.html ) 你能映射一个层次很深的对象吗?

如果我有一个具有多个级别的对象:

var data = {
    name: 'Graham',
    children: [
        {
            name: 'Son of Graham',
            children: [
                {
                    name: 'Son of Son of Graham',
                    children: [
                        {
                            ... and on and on....
                        }
                    ]

                }
            ]
        }
    ]
}

如何将其映射到 javascript 中的自定义类:

var mapping = {
    !! your genius solution goes here !!

    !! need to create a myCustomPerson object for Graham which has a child myCustomerPerson object 
    !! containing "Son of Graham" and that child object contains a child myCustomerPerson 
    !! object containing "Son of Son of Graham" and on and on....

}

var grahamModel = ko.mapping.fromJS(data, mapping);

function myCustomPerson(name, children)
{
     this.Name = ko.observable(name);
     this.Children = ko.observableArray(children);
}

映射插件能否递归地将这些数据映射到我的自定义对象的层次结构中?

Using the knockout mapping plugin ( http://knockoutjs.com/documentation/plugins-mapping.html ) can you map a deeply hierachical object?

If I have an object with multiple levels:

var data = {
    name: 'Graham',
    children: [
        {
            name: 'Son of Graham',
            children: [
                {
                    name: 'Son of Son of Graham',
                    children: [
                        {
                            ... and on and on....
                        }
                    ]

                }
            ]
        }
    ]
}

How do I map it to my custom classes in javascript:

var mapping = {
    !! your genius solution goes here !!

    !! need to create a myCustomPerson object for Graham which has a child myCustomerPerson object 
    !! containing "Son of Graham" and that child object contains a child myCustomerPerson 
    !! object containing "Son of Son of Graham" and on and on....

}

var grahamModel = ko.mapping.fromJS(data, mapping);

function myCustomPerson(name, children)
{
     this.Name = ko.observable(name);
     this.Children = ko.observableArray(children);
}

Can the mapping plugin recursively map this data into an hierachy of my custom objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

携余温的黄昏 2024-12-13 06:19:54

像这样的东西(Live copy on js fiddle):

CSS:

.left {
    float: left;
}

.clear {
    clear: both;
}​

HTML:

<p>Current: 
    <a href="#" data-bind="visible: (stack.length > 0), text: selectedNode().name, click: selectParentNode"></a>
    <span data-bind="visible: (stack.length <= 0), text: selectedNode().name"></span>
</p>
<p class="left">Children: </p>
<ul class="left" data-bind="template: {name: 'childList', foreach: selectedNode().children}"></ul>

<script type="text/html" id="childList">
    <li data-bind="click: function(){nodeViewModel.selectChildNode($data)}">
        <a href="#">A${name}</a>
    </li>
</script>

<br /><br />
<ul class="clear" data-bind="template: {name: 'backBtn'}"></ul>

<script type="text/html" id="backBtn">
    <a href="#" data-bind="visible: $data.selectedNode().back, click: function() { nodeViewModel.selectBackNode($data.selectedNode().back) }">Back</a>
</script>​

JavaScript:

var node = function(config, parent) {
    this.parent = parent;
    var _this = this;

    var mappingOptions = {
        children: {
            create: function(args) {
                return new node(args.data, _this);
            }
        }
    };

    ko.mapping.fromJS(config, mappingOptions, this);
};

var myModel = {
    node: {
        name: "Root",
        children: [
            {
            name: "Child 1",
            back: 1,
            children: [
                {
                name: "Child 1_1",
                back: 1,
                children: [
                    {
                    name: "Child 1_1_1",
                    back: 4,
                    children: [
                        ]},
                {
                    name: "Child 1_1_2",
                    back: 2,
                    children: [
                        ]},
                {
                    name: "Child 1_1_3",
                    back: 1,
                    children: [
                        ]}
                    ]}
            ]},
        {
            name: "Child 2",
            back: 1,
            children: [
                {
                name: "Child 2_1",
                back: 1,
                children: [
                    ]},
            {
                name: "Child 2_2",
                back: 1,
                children: [
                    ]}
            ]}
        ]
    }
};

var viewModel = {

    nodeData: new node(myModel.node, undefined),

    selectedNode: ko.observable(myModel.node),

    stack: [],

    selectBackNode: function(numBack) {

        if (this.stack.length >= numBack) {
            for (var i = 0; i < numBack - 1; i++) {
                this.stack.pop();
            }
        }
        else {
            for (var i = 0; i < this.stack.length; i++) {
                this.stack.pop();
            }
        }

        this.selectNode( this.stack.pop() );
    },

    selectParentNode: function() {
        if (this.stack.length > 0) {
            this.selectNode( this.stack.pop() );
        }
    },

    selectChildNode: function(node) {
        this.stack.push(this.selectedNode());
        this.selectNode(node);
    },

    selectNode: function(node) {
        this.selectedNode(node);
    }

};

window.nodeViewModel = viewModel;
ko.applyBindings(viewModel);​

此示例仅映射一组无限嵌套的 JSON 数据,我可以说,从在应用程序中实际使用这个确切的代码来看,效果非常好。

一些额外的函数(例如

selectBackNode 和 selectParentNode)

允许您在树上向上移动。

在浏览示例时,父标签会变成一个链接,允许向上一级,并且某些叶节点有一个后退按钮,允许它们在树上向后移动给定的级别数。

--编辑--

如果您的叶节点没有子数组,您可能会遇到引入模型中不存在的附加数据的问题。

Something like this (Live copy on js fiddle):

CSS:

.left {
    float: left;
}

.clear {
    clear: both;
}​

HTML:

<p>Current: 
    <a href="#" data-bind="visible: (stack.length > 0), text: selectedNode().name, click: selectParentNode"></a>
    <span data-bind="visible: (stack.length <= 0), text: selectedNode().name"></span>
</p>
<p class="left">Children: </p>
<ul class="left" data-bind="template: {name: 'childList', foreach: selectedNode().children}"></ul>

<script type="text/html" id="childList">
    <li data-bind="click: function(){nodeViewModel.selectChildNode($data)}">
        <a href="#">A${name}</a>
    </li>
</script>

<br /><br />
<ul class="clear" data-bind="template: {name: 'backBtn'}"></ul>

<script type="text/html" id="backBtn">
    <a href="#" data-bind="visible: $data.selectedNode().back, click: function() { nodeViewModel.selectBackNode($data.selectedNode().back) }">Back</a>
</script>​

JavaScript:

var node = function(config, parent) {
    this.parent = parent;
    var _this = this;

    var mappingOptions = {
        children: {
            create: function(args) {
                return new node(args.data, _this);
            }
        }
    };

    ko.mapping.fromJS(config, mappingOptions, this);
};

var myModel = {
    node: {
        name: "Root",
        children: [
            {
            name: "Child 1",
            back: 1,
            children: [
                {
                name: "Child 1_1",
                back: 1,
                children: [
                    {
                    name: "Child 1_1_1",
                    back: 4,
                    children: [
                        ]},
                {
                    name: "Child 1_1_2",
                    back: 2,
                    children: [
                        ]},
                {
                    name: "Child 1_1_3",
                    back: 1,
                    children: [
                        ]}
                    ]}
            ]},
        {
            name: "Child 2",
            back: 1,
            children: [
                {
                name: "Child 2_1",
                back: 1,
                children: [
                    ]},
            {
                name: "Child 2_2",
                back: 1,
                children: [
                    ]}
            ]}
        ]
    }
};

var viewModel = {

    nodeData: new node(myModel.node, undefined),

    selectedNode: ko.observable(myModel.node),

    stack: [],

    selectBackNode: function(numBack) {

        if (this.stack.length >= numBack) {
            for (var i = 0; i < numBack - 1; i++) {
                this.stack.pop();
            }
        }
        else {
            for (var i = 0; i < this.stack.length; i++) {
                this.stack.pop();
            }
        }

        this.selectNode( this.stack.pop() );
    },

    selectParentNode: function() {
        if (this.stack.length > 0) {
            this.selectNode( this.stack.pop() );
        }
    },

    selectChildNode: function(node) {
        this.stack.push(this.selectedNode());
        this.selectNode(node);
    },

    selectNode: function(node) {
        this.selectedNode(node);
    }

};

window.nodeViewModel = viewModel;
ko.applyBindings(viewModel);​

This sample just maps an infinitely nested set of JSON data, and I can say from actually using this exact code in application that is works great.

Some of the extra functions like

selectBackNode and selectParentNode

allow you to move back up the tree.

While navigating the example the parent label becomes a link to allow for going up one level, and some of the leaf nodes have a back button that allows them to move back up the tree by a given number of levels.

--EDIT--

If your leaf nodes don't have a children array you might get a problem where additional data is introduced that doesn't exist in the model.

软甜啾 2024-12-13 06:19:54

根据我的经验,我会说它不应该有任何问题。

我将使用以下行 -

var grahamModel = ko.mapping.fromJS(data);

然后在下一行设置断点,查看调试器中生成的对象(chrome 或 FF+Firebug 效果最好)。这样您就会知道 ko.mapping 是否会生成满足您需求的视图模型。

通常,它生成一个对象,其中只有端点(具有值的变量)是 ko.observables。可用于导航数据的任何其他数据时间(例如 ...children: [...)都显示为普通的 javaScript 对象。

From my experience, I would say that it shouldn't have any problems.

I would use the following line -

var grahamModel = ko.mapping.fromJS(data);

Then set a breakpoint on the next line at look at the generated object in your debugger (chrome or FF+Firebug works best). This way you will know if ko.mapping will generate a viewmodel that meets your needs.

Normally, it generates an object where only the end points (variables with values) are ko.observables. Any of the other data times that you can use for navigation through the data, like ... children: [... are shown as ordinary javaScript objects.

如果您不想要嵌套的映射选项(为每个节点级别创建 ko 映射对象),您可以利用 create 的 ko 映射选项让您可以访问父对象。像这样的事情:

function Folder(parent,data) {
    var self = this;
    self.parent = parent;
    ko.mapping.fromJS(data, self.map, self);
}

Folder.prototype.map = {
    'folders': {
        create: function(options) {
            var folder = new Folder(options.parent,options.data);
            return folder;
        }
    }
}

var data = { name:"root", folders: [ {name:"child", folders: [] } ] };
var root = new Folder(null, data);

这样你在类原型(或者可以是任何函数)中只有地图的 1 个副本。如果您希望Folder.parent也成为可观察的,您可以在map函数内执行data.parent =parent;,而不是作为参数传递给Folder构造函数,或者在文件夹内执行此操作构造函数而不是 self.parent =parent;

If you don't want the nested mappingOptions (creating a ko map object for each node level), you can take advantage of the fact the ko mapping options for create give you access to the parent object. Something like this:

function Folder(parent,data) {
    var self = this;
    self.parent = parent;
    ko.mapping.fromJS(data, self.map, self);
}

Folder.prototype.map = {
    'folders': {
        create: function(options) {
            var folder = new Folder(options.parent,options.data);
            return folder;
        }
    }
}

var data = { name:"root", folders: [ {name:"child", folders: [] } ] };
var root = new Folder(null, data);

That way you only have 1 copy of the map, in your class prototype (or could be any function). If you want Folder.parent to be an observable as well, you could do data.parent = parent; inside the map function and not pass as a parameter to your Folder constructor, or do that inside the folder constructor instead of self.parent = parent;

凉宸 2024-12-13 06:19:54

我使用了此 answer 中的方法来创建一个复选框层次结构,其中具有子项的节点是可折叠的,并且当您选中/取消选中其后代的父级被选中/取消选中。

查看模型

var Category = function(data, parent) {
    var self = this;
    self.name = data.name;
    self.id = data.id;
    self.parent = parent;
    self.categoryChecked = ko.observable(false);
    ko.mapping.fromJS(data, self.map, self);
};

// This will add a "map" to our category view model
Category.prototype.map = {
    'sub_categories' : {
        create: function(options){
            var category = new Category(options.data, options.parent);
            category.parent.categoryChecked.subscribe(function(value){
                category.categoryChecked(value);
            });
            return category;
        }
    }
};  

HTML(视图)

    <div data-role="panel" id="left-panel" data-position="left" data-position-fixed="false" data-theme="b">
            <div data-role="collapsible-set" data-bind="template: {name: 'category_collapsible', foreach: sub_categories}" data-mini="true" id="categories" data-iscroll> </div>
        </div><!-- END left panel -->

        <script type="text/html" id="category_collapsible">
            <div class="category_collapsible" data-mini="true" data-content-theme="b" data-inset="true" data-iconpos="right">
                <h3>     
                    <input data-role="none" data-them="b" data-bind='checked: categoryChecked, jqmChecked: true, attr: {id: "category_checkbox_"+id}' class="chk_category" type="checkbox" />
                    <label data-bind='attr: {for: "category_checkbox_"+id}'><span data-bind="text: name"> </span></label>
                </h3>
                <ul data-role="listview" data-bind="template: {name: 'category_list', foreach: sub_categories}">

                </ul>
            </div>
        </script><!-- END category_collapsible template -->

        <script type="text/html" id="category_list">
            <!-- ko if: sub_categories().length==0 -->
                <li data-theme="c">
                    <input data-role="none" data-theme="c" data-bind='checked: categoryChecked, jqmChecked: true, attr: {id: "category_checkbox_"+id}' class="chk_category" type="checkbox"/>
                    <label data-corners="false" data-bind='attr: {for: "category_checkbox_"+id}'>
                        <span data-bind="text: name"> </span>
                    </label>        
                </li>
            <!-- /ko -->
            <!-- ko if: sub_categories().length>0 -->
                <li data-theme="c" data-bind="template: {name: 'category_collapsible', data: $data}"></li>
            <!-- /ko -->
        </script>

I used the approach in this answer to create a hierarchy of checkboxes where nodes with children are collapsible and when you check/uncheck the parent its descendants get checked/unchecked.

View Model

var Category = function(data, parent) {
    var self = this;
    self.name = data.name;
    self.id = data.id;
    self.parent = parent;
    self.categoryChecked = ko.observable(false);
    ko.mapping.fromJS(data, self.map, self);
};

// This will add a "map" to our category view model
Category.prototype.map = {
    'sub_categories' : {
        create: function(options){
            var category = new Category(options.data, options.parent);
            category.parent.categoryChecked.subscribe(function(value){
                category.categoryChecked(value);
            });
            return category;
        }
    }
};  

HTML (view)

    <div data-role="panel" id="left-panel" data-position="left" data-position-fixed="false" data-theme="b">
            <div data-role="collapsible-set" data-bind="template: {name: 'category_collapsible', foreach: sub_categories}" data-mini="true" id="categories" data-iscroll> </div>
        </div><!-- END left panel -->

        <script type="text/html" id="category_collapsible">
            <div class="category_collapsible" data-mini="true" data-content-theme="b" data-inset="true" data-iconpos="right">
                <h3>     
                    <input data-role="none" data-them="b" data-bind='checked: categoryChecked, jqmChecked: true, attr: {id: "category_checkbox_"+id}' class="chk_category" type="checkbox" />
                    <label data-bind='attr: {for: "category_checkbox_"+id}'><span data-bind="text: name"> </span></label>
                </h3>
                <ul data-role="listview" data-bind="template: {name: 'category_list', foreach: sub_categories}">

                </ul>
            </div>
        </script><!-- END category_collapsible template -->

        <script type="text/html" id="category_list">
            <!-- ko if: sub_categories().length==0 -->
                <li data-theme="c">
                    <input data-role="none" data-theme="c" data-bind='checked: categoryChecked, jqmChecked: true, attr: {id: "category_checkbox_"+id}' class="chk_category" type="checkbox"/>
                    <label data-corners="false" data-bind='attr: {for: "category_checkbox_"+id}'>
                        <span data-bind="text: name"> </span>
                    </label>        
                </li>
            <!-- /ko -->
            <!-- ko if: sub_categories().length>0 -->
                <li data-theme="c" data-bind="template: {name: 'category_collapsible', data: $data}"></li>
            <!-- /ko -->
        </script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文