如何映射使用ko.viewmodel计算的字段 [英] How can I map a field computed using ko.viewmodel

查看:76
本文介绍了如何映射使用ko.viewmodel计算的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道我怎么能映射使用ko.viewmodel计算的字段,任何人都知道它是如何完成的?非常感谢您的帮助.

Do not know how I can map a field computed using ko.viewmodel anyone knows how it's done? much appreciate any help.

var model = {
    firstName: "Le gatêau",
    lastName: "Chien",
    items: ['J-Rock', 'J-Pop'],
    itemselected: 'J-Pop',
    all: function(){ return firstName + ', ' + lastName + ', ' + itemselected },
};

很遗憾,我不清楚我正在编辑问题,我正在使用ko.viewmodel插件将对象转换为ko模型,但没有将其转换为ko.compute对象,当要映射的对象定义为ko被认为是计算得出的:

I regret not having been more clear, I edit my question, I am using ko.viewmodel plugin to convert an object to a ko model, but not as a field ko.computed the object is defined to ko when maps to be recognized as one computed:

var updatedModel = {
    firstName: "El pastel",
    lastName: "Perro",
    items: ['Pop', 'Rock'],
    itemselected: 'Rock',
    all: function(){ return firstName + ', ' + lastName + ', ' + itemselected },
};
var viewModel = ko.viewmodel.fromModel(model);
ko.applyBindings(viewModel);

我的代码补全在这里演示

感谢您的答复,我在最终代码中添加了我想要的功能:

Thanks for the replies, I put my final code with the functionality I wanted:

JS:

var options = {
    extend: {
        "{root}": function (m) {
            m.all = ko.computed(function () {
                var item = ko.utils.arrayFirst(m.music(), function (g) {
                    return g.id() == m.selected();
                });
                if (item == null) return '';
                return m.like() + ' ' + item.name();
            });
        }
    }
};
var m1 = '{"like":"Pastel","music":[{"id":1,"name":"J-Pop"},{"id":2,"name":"J-Rock"},{"id":3,"name":"Rock"}],"selected":"3"}';
var m2 = '{"like":"Gatêau","music":[{"id":1,"name":"J-Pop"},{"id":2,"name":"J-Rock"},{"id":3,"name":"Rock"}],"selected":"2"}';
var viewmodel = ko.viewmodel.fromModel(JSON.parse(m1), options);
ko.applyBindings(viewmodel);
setTimeout(function () {
    console.clear();
    ko.viewmodel.updateFromModel(viewmodel, JSON.parse(m2));
}, 2300)

HTML:

Comida:
<input data-bind="value: like" />
<br/>Musica:
<select data-bind="options: music, optionsText: 'name', optionsValue: 'id', value: selected"></select>
<br/>

<h1 data-bind="text: all"></h1>

最终演示在这里最终演示

推荐答案

如果我正确地解决了您的问题,则需要在模型上使用ko.computed属性. ko.viewModel插件提供了options来控制您的viewModel.使用extend选项创建计算的属性all,而不是直接添加到对象.我为此创建了一个小提琴: http://jsfiddle.net/sublimejs/L6Wm3/8/.

If I am getting your problem right, you want a ko.computed property on your model. The ko.viewModel pluggin provides options to control your viewModel. Use the extend option to create the computed property all instead of directly adding to object. I have created a fiddle for same: http://jsfiddle.net/sublimejs/L6Wm3/8/.

这篇关于如何映射使用ko.viewmodel计算的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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