Knockout JS映射插件没有初始数据/空表单 [英] Knockout JS mapping plugin without initial data / empty form

查看:131
本文介绍了Knockout JS映射插件没有初始数据/空表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用knockout和knockout映射插件来促进我们的jQTouch Web应用程序中的数据绑定。我们使用映射插件的原因是能够使用knockout而无需在javascript中手动定义/更改viewmodels。当您从服务器/客户端数据库初始加载数据时,映射插件很有用。

We are using knockout and the knockout mapping plugin to facilitate databinding in our jQTouch web application. The reason we use the mapping plugin, is to be able to use knockout without the need to define/change viewmodels manually in javascript. The mapping plugin works great when you have an initial load of data from the server/client side database.

我们遇到的问题是我们有一些屏幕/视图,其中有一种形式可能没有任何初始数据。如果没有这个初始数据,映射插件就无法生成viewmodel(ko.mapping.fromJS)。这意味着我们仍然需要手动定义视图模型的大部分视图。

The problem we are having is that we have some screens/views which have a form in which it is possible that there isn't any initial data. Without this initial data, the mapping plugin can't 'generate' the viewmodel (ko.mapping.fromJS). This means that we still need to define our viewmodels by hand for large parts of our views.

假设这是一个映射插件的场景我应该错了)支持?我的意思是,这意味着映射插件仅在您始终具有初始数据加载的情况下可用。

Am I wrong in assuming that this is a scenario which the mapping plugin (should) support? I mean, this means that the mapping plugin is only usable in scenarios in which you always have an initial load of data.

推荐答案

除了手动管理视图模型之外,还有几个选项。映射插件支持 create 回调,可以自定义如何创建它。这可用于向对象添加默认属性(如果它们恰好丢失)。

A couple of options for you besides just manually managing your view model. The mapping plugin supports a create callback that lets you customize how it gets created. This can be used to add default properties to an object, if they happen to be missing.

这样的事情:http://jsfiddle.net/rniemeyer/WQGVC/

另一种方法是使用创建属性的绑定失踪。它可能看起来像:

Another alternative is to use a binding that creates properties that are missing. It might look like:

//create an observable if it does not exist and populate it with the input's value
ko.bindingHandlers.valueWithInit = {
    init: function(element, valueAccessor, allBindingsAccessor, data) {
        var property = valueAccessor(),
            value = element.value;

        //create the observable, if it doesn't exist 
        if (!ko.isWriteableObservable(data[property])) {
            data[property] = ko.observable();
        }

        //populate the observable with the element's value (could be optional)
        data[property](value);

        ko.applyBindingsToNode(element, { value: data[property] });
    }
}

你会像这样使用它(需要通过属性为字符串,否则会出错):

You would use it like this (need to pass the property as a string, otherwise it will error):

<input data-bind="valueWithInit: 'name'" />

此处示例: http://jsfiddle.net/rniemeyer/JPYLp/

这篇关于Knockout JS映射插件没有初始数据/空表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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