【问题标题】:Update var using .change?使用 .change 更新 var?
【发布时间】:2018-06-29 14:59:58
【问题描述】:

在 80% 的案例中,我开始面临一个重要的问题。

假设我有这个:

var bcount = properties.count;
favicon.badge(bcount);
bcount.change(function() { favicon.badge(bcount); });

properties.count = 它是一个随用户操作而变化的数字。 favicon.badge 它是一个显示动作的 javascript,效果很好。

我尝试在 bcount var 上使用 .change,但正如我所想的那样给了我错误,因为它不是一个元素。 当值发生变化时,有什么方法可以监听 var 吗?

我面临的问题是,当计数更新时,会出现一个新数字。刷新页面后才会更新。

谢谢!!

编辑:我正在尝试设置 getter 和 stter:

var bcount = {
  a: properties.count,
  get b() { 
    return this.a;
  },
  set c(cname) {
    this.a;
  }
};

这样好吗?现在我该如何发起通话?

【问题讨论】:

  • jquery 函数在 DOM 元素上执行,而不是在 javascript 变量上。如果要更改变量值,请使用赋值运算符=。如果您想要一个变量更改事件的侦听器(开箱即用不存在),那么已经有关于它的资源。
  • 感谢您的回答,您能给我举个例子来说明如何使用“分配运算符”或链接吗?或者其他的东西?谢谢!!
  • 在 bcount 上尝试 getter 和 setter。 developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
  • 谢谢,我马上试试!

标签: javascript jquery


【解决方案1】:

我认为您需要 getset 功能。您可以将逻辑放入这些函数中,它们会在变量 get 和 set 中执行您想要的操作。

看这个:es5-getters-setter

以上链接的示例:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}

person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin

编辑:

每个字段都有其getset。如果您想让其他人在阅读您的代码时感到困惑,请这样做。但正确的是:

var properties = {
  _count:0, // you hold count value here
  get count() { // every time you get "properties.count" this function will run
    // place for your code that must run on get, like "var bcount = properties.count"
    return this._count;
  },
  set count(new_count) { // every time you want to do "properties.count = some_int" this function will run
    // place for your code that must run on set, like "properties.count = some_int"
    this._count = new_count;
  }
};
// usage
properties.count = 10; // "properties._count" is "10" now
var bcount = properties.count; // you just got "properties._count" value

【讨论】:

  • 谢谢,但是 properties.count 属于一个字段,所以可以使用相同的标识符吗?
  • getset 函数不会向您的属性添加 2 个字段。他们只是一个。您只需要另一个字段(主要是私有字段)来在该字段上存储这些函数所需的数据。因此,正如我所写,您可以将 properties.count 作为字段而不是函数访问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2020-08-21
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多