简体   繁体   English

KnockoutJS:通过自定义绑定将属性添加到ViewModel

[英]KnockoutJS: Add Property to ViewModel through Custom Binding

I'm adding a custom binding to my page. 我正在向页面添加自定义绑定。 Within it, I'd like to save one of the objects I create as a property of the viewModel. 在其中,我想将创建的对象之一保存为viewModel的属性。 When I do this, I get "undefined" when I try and access it outside of the binding. 当我这样做时,当我尝试在绑定之外访问它时,我得到“ undefined”。 Why? 为什么? Here is a reduced down example: 这是一个简化的示例:

HTML: HTML:

<div id = "myDiv" data-bind = "fooAdd: myFoo"></div>

JavaScript: 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());

From your sample, you're setting the new property in the init, which gets called only at the time of applying the bindings, but you are trying to access it in the constructor of the view model. 从您的示例中,您将在init中设置新属性,该属性仅在应用绑定时被调用,但是您试图在视图模型的构造函数中对其进行访问。 Try console.log(viewmodel._foo) after the applyBindings call. 在applyBindings调用之后尝试console.log(viewmodel._foo)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM