Domanda

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.

È stato utile?

Soluzione

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)
    })
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top