简体   繁体   English

为什么数据绑定在字符串中不起作用?

[英]Why data-bind doesn't work inside a string?

I am trying to add a button to a tool-tip (Info Windows) in Google Maps.我正在尝试向 Google 地图中的工具提示(信息窗口)添加一个按钮。 I generate this button inside a string and I just add this string to the content of the tool-tip so it generates the button inside the tool-tip.我在一个字符串中生成这个按钮,我只是将这个字符串添加到工具提示的内容中,以便它在工具提示中生成按钮。 The problem is that the data-bind doesn't seem to work this way.问题是数据绑定似乎不是这样工作的。

Here is an image of the situation: https://imgur.com/gpyl0Mr这是情况的图像: https : //imgur.com/gpyl0Mr

function MapViewModel() {
  var self = this;
  self.removeTurbineColor = ko.observable(false);

  function addToolTip(currentTurbine, turbineIcon){
    var turbineToolTip = "name";

    turbineToolTip += "<button id='remove-emergency-turbine' data-bind='click: 
    removeTurbineColor'> remove </button>";


   self.removeTurbineColor.subscribe( function() {
     console.log("turbine changed");
   });

  var infoWindowTurbine = new google.maps.InfoWindow({content: turbineToolTip});

  if(turbineIcon){
    google.maps.event.addListener(turbineIcon, "click", function(){
      infoWindowTurbine.setPosition(turbineIcon.getPosition());
      infoWindowTurbine.open(self.map, turbineIcon);
     });
   }

 }
}

I expect the output in the console to be "turbine changed" when I click on the button, but nothing appears.当我点击按钮时,我希望控制台中的输出是“涡轮机改变”,但什么也没有出现。

Knockout bindings are set up when you first call ko.applyBindings .当您第一次调用ko.applyBindings时,会设置 Knockout 绑定。 It won't apply bindings for elements inserted after that initial binding.它不会对在初始绑定之后插入的元素应用绑定。

Instead of inserting HTML, you could append a button element and manually attach a click event handler.您可以附加一个按钮元素并手动附加一个单击事件处理程序,而不是插入 HTML。

Or, probably better, you could hard-code the button HTML so its bindings are applied at ko.applyBindings , and toggle its visibility with another observable.或者,可能更好的是,您可以对按钮 HTML 进行硬编码,以便在ko.applyBindings应用其绑定,​​并使用另一个可观察对象切换其可见性。

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

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