Knockout客户绑定valueAccessor()不是一个函数

时间:2016-10-26 08:35:51

标签: javascript knockout.js icheck

我为icheck插件创建了一个客户绑定,我想在选中复选框时更新绑定对象。

这是我的viewModel

            var userViewModel = function () {
            var self = this;
            self.UserFullData = ko.observable();
            self.loadObject = function () {
                $.ajax({
                    type: 'GET',
                    contentType: 'application/json',
                    url: '../UserData.do/GetUser?id=1',
                    success: function (result) {
                        var data = JSON.parse(result);
                        if (data) {

                            self.UserFullData(data);  //data from ajax
                        }
                    }
                });
            };

Ajax数据:

{"User":{"ID":1,"HumanID":1,"LoginName":"cccc","LoginPass":"eeee","PermissionID":1,"DepartmentID":8,"Name":"cz","Sex":1,"SexStr":null,"EName":"cheo","NickName":"b","Company":null,"Address":null,"Email":null,"Country":0,"Province":0,"City":0,"Area":0,"PersonType":0,"Mobile":null,"PhoneNumber":"123456","MSN":null,"Fax":null,"Extension":null,"LastLoginTime":"0001-01-01T00:00:00","Position":null},"PermissionGroup":[{"ID":1,"Title":"a","View":false,"Update":true}]}

HTML:

'查看'是Array of FullUserData.PermissionGroup

中的属性
     <div class="box" data-bind="with:UserFullData">
 <div data-bind="foreach:PermissionGroup">
    <input type="checkbox" class="minimal" style="position: absolute; opacity: 0;" data-bind="iCheckBinding:View">

以下是客户绑定功能:

            ko.bindingHandlers.iCheckBinding = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                $(element).iCheck({
                    checkboxClass: 'icheckbox_minimal-blue',
                    radioClass: 'iradio_minimal-blue'
                });
                var value = valueAccessor();
                var valueUnwrapped = ko.unwrap(value);
                if (valueUnwrapped) {
                    $(element).iCheck('check');
                }
                else {
                    $(element).iCheck('uncheck');
                }


                $(element).on('ifChanged', function () {
                    var newValue = this.checked;
                    var observable = valueAccessor();
                    //observable always not a function
                    observable(newValue);

                });
            }
        };

现在其他一切对我都很好..只是可观察(newValue)不是一个让我困扰的功能,我无法更新我的对象。

谁知道呢?

1 个答案:

答案 0 :(得分:0)

你期望View成为一个可观察者,但是你没有做任何让它成为可观察的事物。该代码中唯一可观察的是UserFullData,您在此处设置:

self.UserFullData = ko.observable();

success函数中的代码无法在 中创建任何可观察的内容:

success: function (result) {
    var data = JSON.parse(result);
    if (data) {
        self.UserFullData(data);  //data from ajax
    }
}

如果您希望该结构中的View能够被观察到,那么您必须这样做。