使用KnockoutJS自动绑定 [英] Using KnockoutJS automatic binding

查看:73
本文介绍了使用KnockoutJS自动绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将List => List => List => List对象绑定到Knockout JS视图模型中.

我来自$ getJSON的数据如下

My data from $getJSON is as follows

我尝试了映射插件来创建一个像:-这样的视图模型 var viewModel = ko.mapping.fromJS(d.organisationsData);

I tried the mapping plugin to create a viewmodel like :- var viewModel = ko.mapping.fromJS(d.organisationsData);

,问题是我不知道为什么(/是否)映射正确发生.

and the problem is I dont know why (/whether) mapping is happening properly.

我无法使用数据绑定来遍历此List和innerList属性

这是我的ViewModel对象

This is my ViewModel object

我尝试使用数据绑定:for-每个ListOfOrg进行迭代,它显示未找到绑定错误ListOfOrg.

I tried iterating using data-bind: for-each ListOfOrg and it is showing Binding error ListOfOrg is not found.

<ul data-bind="foreach:ListOfOrg">

我是KnockoutJS的新手,所以我想我在做些很傻的事情,如果是的话,请指向正确的方向.

推荐答案

好吧,让我们看一个简单的示例,假设我们想在页面上显示一些活动.

Ok let's go through a simple example imagining we want to show some activities on a page.

  1. 假设您返回的数据是所有具有特定属性的活动的枚举,那么您的活动可能看起来像这样:

var ActivityType = function (data) {
       var self = this;
       self.Id = ko.observable(data.Id);
       self.Name = ko.observable(data.Name);
       self.Description = ko.observable(data.Description);
       self.Selected = ko.observable(data.Selected); };

然后您有一个视图模型,该视图模型具有一个名为活动"的属性,该属性需要映射到该活动模型,因此,当您获得活动枚举时,该枚举将自动为该数组中的新活动类型生成相同数量的数字.

Then you have a viewmodel which has a property called Activities which needs to mapped to this activity Model, so when you get your activities enumeration it automatically produces the same of number New ActivityTypes for you in that array.

var activitiesViewModel = {};

因此我们为此定义了一个映射实用程序(简单地说,新的ActivityType是具有不同ID的,然后创建一个新的).

so we define a mapping utility for that (simply saying new ActivityTypes are the ones with a different Id so then create a new one):

var ActivityTypeDataMappingOptions = {
        key: function (data) {
            return data.Id;
        }, create: function (options) {
            return new ActivityType(options.data, null);
        }
    }

所以现在我们需要视图模型上的activity属性:

So now we need the activities property on the view model:

activitiesViewModel.Activities = mapping.fromJS([]);

这意味着根据映射数据创建一个可观察的数组.

This means make an observable array based on the mapping data.

比方说,您定义了一个数据上下文,该数据上下文然后在该回调的回调中为您提供数据:

Let's say you have a datacontext defined that gives you your data then in the callback of that:

datacontext.getActivities(function (data) {
    mapping.fromJS(data.Activities, ActivityTypeDataMappingOptions, activitiesViewModel.Activities);
    ko.applyBindings(activitiesViewModel);
});

mapping.fromJS接受3个参数,第一个是要具有数据的集合,第二个是我们定义的映射实用程序,因此要进行新的活动,最后保留持有可观察集合的视图模型上的属性.

mapping.fromJS takes 3 params, first one the collection thats going to have the data, second one the mapping utility we defined so make new activities out of and last the property on the view model that holds the observable collection.

所以现在您可以像这样使用它:

So now you can use this like:

<ul data-bind="foreach: Activities">
     <li><input type='text' data-bind="value: Name" /></li>
</ul>
<button data-bind="click: updateActivities">Update Activities</button>

  • 注意:在此示例中,视图模型为单例,但您可能希望根据使用情况,使用显示原型模式将其设为可实例化的对象.然后,当您调用ko.applyBindings时,您需要传递新的activityViewModel()作为参数.
  • 现在要更新并发送结果,我们需要定义updateActivities:

    Now for updating and sending back the results we need to define updateActivities:

    activitiesViewModel.updateActivities = function(){
         // Let's say our data context also has a setActivities method that requires a payload of activities object for Post
        datacontext.setActivities({
            // as activitiesViewModel.Activities is an observable array then this will always have the latest values which might have changed in your UI
            activities : ko.toJSON(activitiesViewModel.Activities)
        }, function(data){
         // Lets say the POST will return true if the call was successful
            if (data) alert("all done");
        });
    };
    

    • 您还可以绑定此函数以更改甚至输入的内容,但这将导致太多的API调用,因此我不建议这样做.

      • You can also bind this function to change even of the input but that would be far too many API calls, so I don't recommend it.

        如果要创建许多模型,然后视图模型会使用这些模型,则您会很快意识到您正在做很多服务器端已经完成的建模.如果您编写一些服务器端代码,这些代码会自动生成包含模型的js文件,例如在我的示例中,使用ActivityType,您可以简单地使用requireJS将其导入视图模型文件中,然后在整个应用程序中使用它们.通过仅更新后端中的模型,这将允许在前端自动进行属性名称更改和更新.

        If you are making lots of these models which is then used by a view model you will quickly realize you are doing a lot of modelling that is already done on the server side. If you write some server side code that automatically generates js files containing the model e.g. ActivityType in my example, you can simply use requireJS to import them in the view model file and then use them across the application. This will allow property name changes and updates to be automatically available on the front end by only updating the model in the backend.

        这篇关于使用KnockoutJS自动绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆