4

我正在尝试设置一个paper-checkbox内部元素。我希望复选框的选中状态由 ajax 调用的响应控制。

HTML:

<epic-list-episode checked="<%= episode.seen? %>">
  <p><strong><%= episode.show.name %></strong></p>
</epic-list-episode>

自定义元素:

<polymer-element name="epic-list-episode" attributes="checked">

  <template>
    <link rel="stylesheet" href="epic-list-episode.css.scss" />
    <div horizontal layout center>
      <div flex>
        <content></content>
      </div>
      <div vertical layout>
        <paper-checkbox checked?="{{checked === 'true'}}" on-change="{{changeHandler}}"></paper-checkbox>
      </div>
    </div>
  </template>

  <script>
    Polymer({
      changeHandler: function(event) {
        //Send ajax, wait for error/success callback
        //checkbox.checked = response from ajax
      }
    });
  </script>

</polymer-element>

如何做到这一点?我已经尝试过return false,但复选框仍然会执行其切换动画。

为了澄清,这是我想要的流程:

  1. 复选框未选中
  2. 我单击复选框(我不希望它切换)
  3. Ajax 请求被发送出去
  4. 等待回调
  5. 如果成功,切换复选框的状态
4

2 回答 2

2

我认为您根本不需要该checked属性。

您可以做的是,在on-change调用 时,checked将 back 的属性设置paper-checkbox为其先前的值。然后在 ajax 回调之后,将其设置回应有的状态。

changeHandler: function (event, detail, sender) {
    this.$.checkbox.checked = !this.$.checkbox.checked;

    // give the checkbox a little loading animation
    var loading = new CoreAnimation();
    loading.duration = 750;
    loading.easing = 'ease-in';
    loading.keyframes = [{ opacity: 1, transform: "scale(1)" }, { opacity: 0.4, transform: "scale(0.9)" }];
    loading.direction = 'alternate';
    loading.iterations = '1000';
    loading.target = this.$.checkbox;
    loading.play();

    // give it a little delay to act like a callback
    this.job('delay', function () {
        // stop the animation
        loading.finish();

        this.$.checkbox.checked = !this.$.checkbox.checked;
    }, 3000);
}

请注意,我还包含了一些动画代码,让用户感觉像是在paper-checkbox做某事,以获得更好的用户体验。请参阅此jsbin以获取工作示例。

于 2015-02-09T10:13:29.083 回答
1

有几种方法可以真正做到这一点。我做了这个 plunker 来展示我做这件事的两种方法。http://plnkr.co/edit/xqHCSvs63u4bdFJYM6TF?p=preview

使用声明性绑定

<paper-checkbox checked="{{checked}}" on-change="{{changeHandler}}"></paper-checkbox>

在你的脚本中

this.checked = true;

和纯js

<paper-checkbox id="box" on-change="{{changeHandler}}"></paper-checkbox>

然后在你的脚本中

var box = document.querySelector("#box");
box.checked = true;
于 2015-02-09T16:05:28.193 回答