【问题标题】:Using Knockout ko template binding for google maps infowindow使用谷歌地图信息窗口的 Knockout ko 模板绑定
【发布时间】:2017-06-26 14:17:26
【问题描述】:

我正在尝试使用敲除模板来填充我的 google 地图标记信息窗口,其中包含一个点击事件,以在模式中显示 wiki 文章。现在,我的标记是空白的,我没有收到任何错误。关于我做错了什么有什么想法吗?

html sn-p

<script type="text/html" id="info-template">

            <div data-bind="with: currentLocation">

               <div id="m-title" data-bind="text: title"></div>

            </div>

            <button id="wiki-a" data-bind="click: toggleWiki">

                Wikipedia Articles

            </button>

            <div id="pano"></div>

        </script>

js sn-p

infowindow.setContent('<div id="info-window" data-bind="template:' + 
                        '{ name: \'info-template\'}"></div>');

完整代码https://github.com/CHBaker/Neighborhood-map

【问题讨论】:

    标签: javascript templates google-maps-api-3 knockout.js


    【解决方案1】:

    Google setContent 方法中不能直接添加 Knockout Js 模板,该方法具体需要一个字符串或 html 节点来渲染。 见docs

    因此,您添加的内容将被添加为字符串或 html 节点。但在您的情况下,它似乎是字符串,因为您传递的敲除模板不是有效的 DOM 节点,将被视为常规字符串。这里的关键是先渲染html,然后将其内容设置为infowindow。

    用这个更新你的infowindow.setContent 方法

    infowindow.setContent(document.getElementById("info-template").innerHTML);
    

    希望对你有帮助!

    【讨论】:

    • 这会将 html 放入信息窗口,但这会阻止模板中的数据绑定点击事件吗?
    • 可以在setContent方法后绑定事件ko.applyBindings(&lt;YourViewModel&gt;, &lt;your template node&gt;)
    • 这可能是一个愚蠢的问题,但我可以在 setContent 方法之后的下一行中设置它吗?我应该使用我已经拥有的 ko.applyBindings 方法将其设置在我的 js 文件的底部吗?
    • 是的,你应该在setContent之后调用该方法,因为你想在弹出窗口添加后立即设置点击事件的绑定。在你的 Js 底部添加是行不通的。只是一个建议,当我查看您的代码库时,您需要对代码进行重大重构。当我在寻找适当的上下文时,我无法为你解决它。让我知道它是否能解决您的问题。
    • 就添加 applyBindings 方法而言,我不能有两个 apply 绑定方法。我自己也在为此苦苦挣扎......寻找一个我不必重构我的整个代码库的修复程序。感谢您提供更多帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多