【问题标题】:CanJS on click outside of component effecting componentCanJS点击组件外部影响组件
【发布时间】:2016-09-02 15:13:49
【问题描述】:

我想在<some-component> 中添加一个对按钮作出反应的事件监听器。

<some-component></some-component>
<button class="click">click here</button>

我相信这真的很简单。我对 CanJS 非常陌生,并且正在研究它。

<can-component tag="some-component">
<style type="less">
    <!-- stuff -->
</style>
<template>
    <!-- stuff -->
</template>
<script type="view-model">
import $ from 'jquery';
import Map from 'can/map/';
import 'can/map/define/';

export default Map.extend({
  define: {
    message: {
      value: 'This is the side-panels component'
    }
  }
});
</script>
</can-component>

我尝试在组件中添加$('body').on('click', '.click', function() {});,但它似乎不起作用。阅读了很多文档,但我仍然缺少一些基本的理解。

更新

我试过了:

<some-component-main>
    <some-component></some-component>
    <button class="click">click here</button>
</some-component-main>

使用some-component-main中的事件监听器

events: {
  ".click click": function(){
    console.log("here I am");
  }
},

但这也没有用。

【问题讨论】:

    标签: canjs donejs


    【解决方案1】:
    <some-component-main>
        <some-component></some-component>
        <button class="click">click here</button>
    </some-component-main>
    

    在 some-component-main 中使用事件监听器

    events: {
      ".click click": function(){
        console.log("here I am");
      }
    },
    

    一旦我意识到以数字结尾的组件会导致其他阻止它的问题,这确实有效。

    【讨论】:

      【解决方案2】:

      您可以使用{^property-name}{^@method-name} 语法使组件内的内容对父范围可用。在这里阅读:https://canjs.com/docs/can.view.bindings.toParent.html

      这是一个小提琴:http://jsbin.com/badukipogu/1/edit?html,js,output

      在下面的示例中, 实现了一个doSomething 方法,并且我们在单击时调用该方法的按钮。我们将该方法公开为“doFooBar”。

      <my-component {^@do-something}="doFooBar" />
      <button ($click)="doFooBar">Button</button>
      

      和代码:

      can.Component.extend({
        tag: "my-component",
        template: can.view('my-component-template'),
        viewModel: can.Map.extend({
          doSomething: function () {
            alert('We did something');
          }
        })
      });
      

      但是为什么示例使用^@do-something="..." 而不是^@doSomething="..."??

      DOM 节点属性是大小写不敏感,因此无法区分doSomething=""DoSomEthiNg=""DOSOMETHING="" - 这三个都是等价的。 CanJS 遵循浏览器的工作方式,将带有破折号的属性转换为驼峰式,反之亦然。

      考虑原生数据属性 - 如果您执行 &lt;div data-my-foo="my bar"&gt; 之类的操作,则可以通过 JavaScript 访问该值,方法是执行 [div].dataset.myFoo(注意 camelCasing)。这同样适用于 css 使用“背景颜色”但 javascript 使用 backgroundColor 的 css 属性。 CanJS 遵循这个约定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-27
        • 1970-01-01
        • 2017-12-16
        • 2014-07-12
        • 2019-06-20
        相关资源
        最近更新 更多