KnockoutJS and binding a single object to a viewmodel

ⅰ亾dé卋堺 提交于 2019-12-08 06:42:44

问题


I've been round and round on this and don't see where things are going wrong. Maybe you can help please.

There are multiple view models setup:

var viewModels = {
    emailTemplateViewModel: {
        subject: new ko.observable('dd'),
        emailName: new ko.observable('dd'),
        emailAddress: new ko.observable('dd'),
        body: new ko.observable('dd')
    },
    deviceSettingsViewModel: {
        managerName: new ko.observable('')    
    }
}

ko.applyBindings(viewModels);

And I'm trying to populate one of the view models with JSON returned from the server (this is correct and properly formatted).

function LoadEmailTemplate() {
    $.getJSON('/EmailTemplate/Template', function (data) {
        viewModels.emailTemplateViewModel = ko.mapping.fromJS(data);
        ko.applyBindings(viewModels.emailTemplateViewModel);
    })
}

However when I run this I get the following error: "Uncaught Error: You cannot apply bindings multiple times to the same element."

But all the documentation I read shows the binding occurring after the mapping.

If I take the binding out from the LoadEmailTemplate function out there are no errors at runtime but the page shows the default values 'dd', not those that should have been mapped from the JSON response.

The function is triggered like this:

<li data-bind="click: LoadEmailTemplate"><a href="#"><i class="glyphicon glyphicon-chevron-right pull-right"></i>Email Template</a></li>

I'm trying to use the with-binding as the email template is relative to only a region of the page, e.g.

<div data-bind="with: emailTemplateViewModel">

And the properties:

<input data-bind="value: emailAddress" type="email" class="form-control" id="inputFromEmail">

I know this is working because the form loads with the values set when the viewmodel is first defined. It appears as if it's just the mapping that's misfiring. Any advice would be really appreciated.

Thank you.


回答1:


Two things, 1 - Do not apply bindings multiple times, even if that works it will cause issues later down the road.
2 - When you get the object from the ajax call do not overwrite your existing object, doing this will break your bindings, instead set your existing object values to the new values.

function LoadEmailTemplate() {
    $.getJSON('/EmailTemplate/Template', function (data) {
        viewModels.emailTemplateViewModel.subject(data.subject);
        viewModels.emailTemplateViewModel.emailName(data.emailName);
        viewModels.emailTemplateViewModel.emailAdrress(data.emailAddress)
        viewModels.emailTemplateViewModel.body(data.body)
    })
}


来源:https://stackoverflow.com/questions/22264252/knockoutjs-and-binding-a-single-object-to-a-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!