javascript - 在 Polymer 中不使用 'this.attributeName' 表示法访问数据绑定(bind)属性

标签 javascript data-binding polymer

我正在尝试将sweetalert2与自定义html一起使用,其中包含具有我想要访问的数据绑定(bind)的 polymer 元素,但我无法使用“this.attributeName”表示法获取数据。我认为这是由于甜蜜警报被附加到正在创建警报的元素上方的 DOM,但我可能是错的,是否有解决方法?我已经提供了用于创建警报的代码,并且在解决方案中我试图解决这个问题。

            swal({
                title: 'Blah Blah',
                html: 
                '<some-el id="days" chosen-days="{{newCDays}}"></some-el>\
                <time-input id="start" time$="{{newSTime}}" hour12 clamp="seconds"></time-input>\
                <time-input id="end" time$="{{newETime}}" hour12 clamp="seconds"></time-input>',
                confirmButtonText: 'Done',
                preConfirm: function() {
                    return new Promise((resolve, reject) => {
                        resolve({
                            days: document.getElementById('days').getAttribute("chosen-days"),
                            start: document.getElementById('start').value,
                            end: document.getElementById('end').time,
                        });
                    });
                }
            });

最佳答案

swal html 中没有数据绑定(bind)

Polymer 数据绑定(bind)仅在 Polymer 模板内工作,因此在 html 中使用该语法swal领域将导致将文字值分配给属性。在以下示例中,<paper-input>.value设置为"{{myValue}}"从字面上看(包括大括号)。请注意,它不会创建 <paper-input>.myValue .

swal({
  html: '<paper-input no-label-float value="{{myValue}}"></paper-input>'
  ...
})

html不应包含数据绑定(bind)。它应该看起来像这样:

swal({
  html: '<paper-input no-label-float></paper-input>'
  ...
})

访问元素属性

preConfirm函数,您可以从 html 查询元素字段,并按名称访问该元素的属性:

swal({
  preConfirm: async () => {
    console.log({
      noLabelFloat: document.getElementById('myInput').noLabelFloat
    });
  }
  ...
})

原生事件绑定(bind)

在您的 Codepen 中,您表明 <input>像这样使用:

<input type="text" value$="{{testAttr}}">

基于您在 swal 中的绑定(bind)的html ,我认为您假设上面的数据绑定(bind)会设置 <x-foo>.testAttr<input>.value ,但这实际上是不正确的。给定一个本地人 <input>元素,你必须使用 Polymer 的 native event-binding syntax :

<input type="text" value="{{testAttr::input}}">

设置 <x-foo>.testAttr<input>.value<input>提出input事件。它相当于:

// in x-foo script
myNativeInput.addEventListener('input', () => {
  this.testAttr = myNativeInput.value;
});

demo

关于javascript - 在 Polymer 中不使用 'this.attributeName' 表示法访问数据绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819946/

相关文章:

javascript - 如何知道传递给函数的参数的 var 名称?

c# - <%# %>有什么用

html - Styling polymer - 一次适用于所有浏览器

css - 将元素添加到水平布局而不适合容器

javascript - Polymer 从 firebase 实时数据库更新 javascript 数组

javascript - 简单的 Javascript 字符串操作

javascript - 如何将 Bootstrap 选项卡设置为事件状态?

c# - 如何转换字符串数据:audio/ogg;base64 to file wav in C#

c# - WPF 双向绑定(bind)到静态类属性

wpf - ViewModel 构造函数包含 WPF 中的参数