【问题标题】:How to update property from function in Aurelia如何从 Aurelia 中的函数更新属性
【发布时间】:2015-07-15 10:59:19
【问题描述】:

我想在推送操作中刷新属性的值,但我不知道如何从函数访问该属性!

export class Datas {
    prop1 = "my val";
}

var connection = new WebSocket('ws://localhost:8787', 'json');
connection.onmessage = function (e) {
     // prop1 of Datas = e.data;
};

有什么想法吗?

编辑:页面加载后,我想在收到推送消息时刷新数据。

编辑 2:测试代码

data.js:

export class Data {
    static information = '';
}

viewModel.js

import {bindable} from 'aurelia-framework';
import { Data } from 'data';

export class ViewModel {
    constructor() { 
        this.informaton = Data.information;
    }

    logState(){
        console.log("state of Data.information : " + Data.information);
        console.log("state of this.information : " + this.information);
    }
}

var connection = new WebSocket('ws://localhost:8787', 'json');
connection.onmessage = function (e) {
    Data.information = e.data;
    console.log("receiving a message : Data.information = " + Data.information);
};

viewModel.html:

<template>
   <span id="spanAff">${information}</span>
   <br/>
   <input type="button" value="log" click.trigger="logState()" />
</template>

日志:

"接收消息:Data.information = 4"
“数据状态。信息:4”
“this.information 的状态:未定义”

【问题讨论】:

    标签: javascript ecmascript-6 aurelia


    【解决方案1】:

    我在另一个论坛上得到了这个解决方案:

    export class ViewModel {
      constructor() { 
        this.information = 'my val';
        var connection = new WebSocket('ws://localhost:8787', 'json');
        connection.onmessage = e => {
            this.information = e.data;
        };
      }
    }
    

    【讨论】:

    • 啊是的,就是这么简单,不是吗? :) 我已经更新了您的解决方案。您不需要可绑定的导入。此外,如果您使用箭头函数,则不需要 myModel 变量。试一试。
    • 感谢您的更正。是的,这真的很简单!
    猜你喜欢
    • 2015-11-16
    • 2016-06-08
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多