Javascript/Ember - 切换变量的布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21942180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:03:52  来源:igfitidea点击:

Javascript/Ember - Toggle Boolean Value of Variable

javascripthtmlember.jsbooleantoggle

提问by Ian S

I know that there is the .set() method to set a boolean to true or false but I want to know if there a method like .set() except it Toggles the value of a boolean.

我知道有 .set() 方法可以将布尔值设置为 true 或 false 但我想知道是否有类似 .set() 的方法,除了它切换布尔值的值。

In this case the boolean isEditing is being set to 'true'.

在这种情况下,布尔值 isEditing 被设置为“true”。

isEditing:false,
actions: {
  edit: function(category){
    category.set('isEditing', true);
    console.log(this.get('isEditing'))
  },
}

Here is the html

这是html

{{#if isEditing}}
  <div class="category-text"> 
    {{view Ember.TextField valueBinding=name action="turnOffEditMode"}}
  </div>
{{else}}
  <div class="category-text"> 
    {{#linkTo 'category' this}}
      {{name}}
    {{/linkTo}}
  </div>
{{/if}}  

回答by Jake Roby

this.toggleProperty('propertyName');

Edit: jsbin for proof

编辑: jsbin 为证

回答by Triode

isEditing:false,
actions: {
    edit: function(category){
        category.set('isEditing', !category.isEditing);
        console.log(this.get('isEditing'))
    }
    toggleEditing : function(category){
    }
}

Toggling the boolean value is what you need. Or yu can change your function like below.

切换布尔值是您所需要的。或者你可以改变你的功能,如下所示。

isEditing:false,
actions: {
    toggleEditing : function(category){
        category.set('isEditing', !category.isEditing);
        console.log(this.get('isEditing'));
    }
}

回答by Cameron

@gravityplanx's answer is great.

@gravityplanx 的回答很棒。

I just want to add that this methodology works beyond the controller as well.

我只想补充一点,这种方法也适用于控制器之外。

For example, if my Model has a Postobject, I can update it from the controller. I just have to pass the object into a controller action.

例如,如果我的模型有一个Post对象,我可以从控制器更新它。我只需要将对象传递给控制器​​操作。

switch_readiness(post) {
    post.toggleProperty('isPublishReady');
}