访问自定义组件数据/方法 [英] Accessing Custom Component Data/Methods

查看:71
本文介绍了访问自定义组件数据/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用自定义组件的html文件.定制组件伸出手并通过bind()方法获取数据.因此,当绑定组件时,它将获取数据并相应地设置属性.此组件还具有Save()方法,该方法在调用时应将对象提交到数据库.

I have an html file that uses a custom component. The custom component reaches out and gets data on the bind() method. So, when the component gets bound, it gets the data and sets the properties accordingly. This component also has a Save() method that, when called, should submit the object to the database.

现在,在我的外部html文件中,我已经导入了此自定义组件.所以我有自定义组件,然后有一个提交按钮(不是自定义组件的一部分),如下所示:

Now, in my outer html file, I have imported this custom component. So I have the custom component and then I have a submit button (not a part of the custom component) like this:

<custom-component></custom-component>
<button click.trigger="submitCustomComponentData()"></button>

在自定义组件视图中没有按钮的原因是,该视图并不总是具有相同的按钮,这将使组件不可扩展.

The reason I don't have the buttons in the custom component view is because that view isn't always going to have the same buttons, which then makes the component non-extendable.

submitCustomComponentData()方法基本上会调用组件VM中的更新方法.

The submitCustomComponentData() method basically calls the update method that is in my component VM.

现在,当页面加载时,一切运行正常.数据被提取,我的所有输入都被先前的数据(来自数据库)预先填充.一切都很棒.但是,当我调用submitCustomComponentData()方法(或单击按钮)时,由于未填充该对象,我收到一个错误.就像我丢失了实例之类的东西.

Now, when when the page loads, everything runs perfect. The data gets pulled in, all of my inputs are pre-populated with the previous data (from the DB). Everything is great. However, when I call the submitCustomComponentData() method (or click the button), I get an error because the object isn't populated. It's like I'm losing the instance or something.

以下是一些重要部分的摘要:

Here is a snippet of some important parts:

这是我的外部html文件的外观.它由自定义组件组成.

This is what my outer html file looks like. It's made up of the custom component.

<template>
    <require from="resources/components/dispatch-questions/dispatch-questions"></require>

<section class="pages au-animate">
    <div class="row" id="dispatch-questions">
        <dispatch-questions></dispatch-questions>
    </div>
</section>

</template>

为此VM注入了dispatch-questions组件,如下所示:

And the VM for this gets injected with the dispatch-questions component like so:

constructor(private router: Router, private dq: DispatchQuestions) {
    }

它还有一个click.trigger方法,应该调用组件中的updateDB方法.那时,组件(应该已经具有在bind()上创建的相同实例)应该将该对象提交给DB.

It also has a click.trigger method that SHOULD call the updateDB method that is in the component. At that moment, the component (which should already have the same instance that got created on bind()) should submit that object to the DB.

但是由于某些原因,该对象为空,因此我收到了错误消息.该组件中的功能是获取this.myObject并将其提交给DB.我想当我从外部VM(而不是组件VM)调用更新功能时,我正在丢失组件的this实例.我认为这就是问题所在.如果这是问题,则不确定如何解决.任何帮助都会很棒!

But I'm getting an error because for some reason, the object is empty. The function in the component is grabbing this.myObject and submitting it to the DB. I think when I'm calling the update function from my outer VM (not the component VM) I'm losing the component's this instance. I think that's the problem..Not sure how to fix it IF that's the issue. Any help would be awesome!

我试图在Gist上创建一个简单的版本. https://gist.run/?id=f07b2eaae9bec27acda296189585ea6c

I've tried to create a simple version on Gist. https://gist.run/?id=f07b2eaae9bec27acda296189585ea6c

推荐答案

对此有一个解释

There's an explanation for that in the documentation.

Aurelia DI使用的一般规则

除了被归类为组件"的那些东西,本质上是通过路由器或组合引擎创建的自定义元素,自定义属性和视图模型之外,所有内容都是应用程序级的单例.您可以通过显式配置来更改路由器和组合创建的组件的寿命.

Everything is an application-level singleton except for those things which are classified as "components", essentially custom elements, custom attributes and view-models created through the router or composition engine. You can change the lifetime of router and composition created components through explicit configuration.

我建议使用EventAggregator而不是注入.这种方法确保了灵活性,可扩展性,并且还防止了紧密耦合.

I'd recommend using EventAggregator instead of injection. This approach ensures flexibility, extensibility and prevents tight-coupling as well.

关于EventAggregator:#1演练Dwayne Charrington a>,文档联系人管理器教程.

About EventAggregator: #1 Walkthrough by Dwayne Charrington, Documentation, Contact Manager Tutorial.

下面是要根据您的情况进行说明的要点: https://gist.run/?id=f66eaa12e4183a72a7cc/a>

Here's a gist to demonstrate it with your scenario: https://gist.run/?id=f66eaa12e4183a72a7a3cc01ce3a8fb5

app.js

让我们假设我们要使用多个Component自定义组件实例.为此,我们可以发布一个带有关联数据的component:save事件.

Let's assume that we'd like to use more than one instances of Component custom component. To achieve that, we can publish a component:save event with associated data.

import { inject } from "aurelia-framework";
import { EventAggregator } from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class App {

  components = [
    { id: 1, name: 'Component #' },
    { id: 2, name: 'Component #' },
    { id: 3, name: 'Component #' }
  ];

  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  SubmitData(opts) {
    this.eventAggregator.publish('component:save', opts);
  }

  // ...
}

component.js

在这里,我们可以预订component:save事件,并检查是否应该继续保存.因此,每个Component实例都应具有唯一的标识(数字,哈希,uid等.).

Here we can subscribe to component:save events and check if we should proceed with saving. For this reason, each Component instances should have a unique identification (number, hash, uid, etc..).

注意:detached方法中有一个重要的清理部分,官方文档中没有明确提及.因此,我首先列出了Dwayne Charrington的博客文章.

Note: there's an important cleanup part in detached method, which isn't mentioned explicitly in official documentation. That's why I've listed Dwayne Charrington's blog post first.

import { inject, bindable } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class Component {

  @bindable
  id;

  object = {};

  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  bind() {
    this.object = {
      "Name": `My name ${this.id}`,
      "Age": 21
    };

    console.log(`component ADDED: #${this.id}`);

    this.subscriber = this.eventAggregator.subscribe('component:save', data => {

      if (data.id === this.id || data.all === true) {
        this.SubmitObjectToDatabase();
        console.log(`component:save SAVED: #${this.id}`, this.object.Name);
      } else {
        console.log(`component:save PASSED: #${this.id}`);
      }

    });
  }

  SubmitObjectToDatabase() {
    console.log(`SubmitObjectToDatabase has been called: #${this.id}`);
  }

  detached() {
    // cleanup
    this.subscriber.dispose();
    console.log(`component REMOVED: #${this.id}`);
  }
}

这篇关于访问自定义组件数据/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆