durandal widget data bind and update by ajax

751 Views Asked by At

I want to use a durandual widget in a view and the widget bind-data should be able to update by the AJAX call from page's view model js. I post my code in following

Here is my page Model: which shoud update email to "Hello after ajax call"

email= ko.observable('Login/Register2222');
        var self = this;
        if ($('#btn-login').html() == 'Login') {
            $.ajax({
                type: "Post",
                url: "api/User/Login",
                data: $('#form-user-login').serialize()
            })
            .success(function (response) {
                if (response == true) {
                    $('#loginModal').modal('hide');
                    $('#LoginBtn').html('My Profile');
                    $("#LoginBtn").attr("data-target", "#profileModal");
                    $.ajax({
                        type: "Post",
                        url: "api/User/getLoginUserInfo",
                        data: $('#form-user-login').serialize()
                    })
                    .success(function (response) {
                        self.email("Hello");
                        router.navigate('#Test');
                    });
                }
            });
        }

Here is my page HTML with widget call

<div data-bind="widget: { kind: 'email', email: email, prompt: 'Email', id: 'Profile_Email', name: 'UserCode' }"></div>

Here is my Widget View Model js

define(['plugins/router', 'durandal/app', 'knockout'], function (router, app, ko, composition) {

function emailWidget() {
    var self = this;
    self.activate = function (options) {
        self.email = ko.observable(ko.unwrap(options.email));
        self.prompt = ko.observable(ko.unwrap(options.prompt));
        self.id = ko.unwrap(options.id);
        self.name = ko.unwrap(options.name);
    };
}

return emailWidget;});

Here is my widget view html

<input type="email"  placeholder="Email" class="form-control" style="text-align:right" data-bind="value: email, attr: { 'id': id, 'name':name}"/>

The email value will update if I am not using it with a widget With a widget the value will stay at 'Login/Register2222' Please Help

1

There are 1 best solutions below

0
On

i have the same problem, and i know the reason why this comes but i dont think that there would be a solution to it.

the place where we do this:

all the accepting variables that are: email, prompt, id and name are not observables. They are coming as properties (in ur case, properties of Options) function (options). and then you assign them to observables.

therefore we have an observable in our caller viewmodel , we have another observable in our widget but the link between the two is a non-observable.