KnockoutJS:通过自定义绑定将 属性 添加到 ViewModel
KnockoutJS: Add Property to ViewModel through Custom Binding
我正在向我的页面添加自定义绑定。在其中,我想将我创建的对象之一保存为 viewModel 的 属性。当我这样做时,当我尝试在绑定之外访问它时,我得到 "undefined" 。为什么?这是一个简化的示例:
HTML:
<div id = "myDiv" data-bind = "fooAdd: myFoo"></div>
JavaScript:
ko.bindingHandlers.fooAdd = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var foo = 1;
viewModel._foo = foo;
}
};
var ViewModel = function(){
var self = this;
self.myFoo = ko.observable({});
console.log(self); //Here I can expand the object returned in
//the console and see that _foo is equal to 1.
console.log(self._foo); //returns undefined
};
ko.applyBindings(new ViewModel());
根据您的示例,您在 init 中设置了新的 属性,它仅在应用绑定时被调用,但您正试图在视图模型的构造函数中访问它.在 applyBindings 调用后尝试 console.log(viewmodel._foo)
。
我正在向我的页面添加自定义绑定。在其中,我想将我创建的对象之一保存为 viewModel 的 属性。当我这样做时,当我尝试在绑定之外访问它时,我得到 "undefined" 。为什么?这是一个简化的示例:
HTML:
<div id = "myDiv" data-bind = "fooAdd: myFoo"></div>
JavaScript:
ko.bindingHandlers.fooAdd = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var foo = 1;
viewModel._foo = foo;
}
};
var ViewModel = function(){
var self = this;
self.myFoo = ko.observable({});
console.log(self); //Here I can expand the object returned in
//the console and see that _foo is equal to 1.
console.log(self._foo); //returns undefined
};
ko.applyBindings(new ViewModel());
根据您的示例,您在 init 中设置了新的 属性,它仅在应用绑定时被调用,但您正试图在视图模型的构造函数中访问它.在 applyBindings 调用后尝试 console.log(viewmodel._foo)
。