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

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

问题描述

我们正在使用淘汰赛和淘汰赛映射插件来促进我们的 jQTouch Web 应用程序中的数据绑定.我们使用映射插件的原因是能够使用淘汰赛,而无需在 javascript 中手动定义/更改视图模型.当您从服务器/客户端数据库初始加载数据时,映射插件效果很好.

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.

我们遇到的问题是我们有一些屏幕/视图的形式,其中可能没有任何初始数据.没有这个初始数据,映射插件不能生成"视图模型(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/

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

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