简体   繁体   English

Angular 2如何防止特定变量的数据绑定

[英]Angular 2 how to prevent data binding for specific variable

So I need to prevent data binding for a specific variable. 因此,我需要防止特定变量的数据绑定。 I want to do it like this: 我想这样做:

// data is mostly an object in my case.
// it would be nice if there's a global solution
function(data) {
    d = data; // variable that changes on user input
    oldD = data; // variable that shouldn't change on user input
}

but whenever I implement code like this the oldD variable will change when the d variable gets changed. 但是每当我实现这样的代码时,d变量更改时oldD变量就会更改。 And I would like to prevent this from happening. 我想防止这种情况的发生。 But how do I prevent such a thing? 但是,如何防止这种情况发生?

You need to assign value without assigning reference of old object. 您需要分配值而不分配旧对象的引用。

Here's solution for JavaScript/Angular. 这是JavaScript / Angular的解决方案。

let oldD = Object.assign({}, data);

Hope this helps. 希望这可以帮助。

Probably you are looking for, How to clone object. 可能您正在寻找如何克隆对象。

function(data) {
    d = data; // variable that changes on user input  

    // creates brand new object with the same data
    let oldD = Object.create(data.constructor.prototype);
    data.constructor.apply(oldD);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM