草庐IT

javascript - 当您在 Ember 函数上绑定(bind) 'this' 时会发生什么?

coder 2025-02-12 原文

我正在努力更好地理解 this Firebase authenticator for Ember SimpleAuth :

import Ember from 'ember';


export default Ember.Controller.extend({


actions: {
    login: function() {
        this.get('session').authenticate('authenticator:firebase', {
            'email': this.get('email'),
            'password': this.get('password')
        }).then(function() {
            this.transitionToRoute('index');
        }.bind(this));
    },
    logout: function() {
        this.get('session').invalidate().then(function() {
            this.transitionToRoute('login');
        }.bind(this));
    }
}
});

谁能解释一下“.bind(this)”在做什么,以及 bind 在这个特定实例中是如何工作的?

编辑:经过一些反射(reflection)和研究,这是我对可能发生的事情提出的解释:

代码的“.then”部分无法访问“this”的原始上下文。 “.bind(this)”将“this”(在本例中为当前 Controller 对象)的值设置为“.then”函数内的“this”。

如果删除“.bind(this)”部分,代码的“transitionTo”部分将不起作用,这一事实可以证明这一点。

另一方面,如果我们编写如下代码,就不需要使用 “.bind(this)”:

import Ember from 'ember';


export default Ember.Controller.extend({


actions: {
    login: function() {
    var _this = this;
        this.get('session').authenticate('authenticator:firebase', {
            'email': this.get('email'),
            'password': this.get('password')
        }).then(function() {
            _this.transitionToRoute('index');
        });
    },
    logout: function() {
      var _this = this; 
        this.get('session').invalidate().then(function() {
            _this.transitionToRoute('login');
        });
    }
}


});

想法?

最佳答案

What happens when you bind 'this' on an Ember function?

在您的示例中,.bind() 未用于 Ember 函数。它用于通常的匿名函数(回调)。因此,您的问题与 Ember 无关。

我所说的回调是指作为参数传递的匿名函数,而不是分配给对象的属性。

这样的函数会绑定(bind)到window,即。 e.函数中的 this 将返回 window

访问外部作用域的传统方法是将 this 分配给外部作用域中的变量,然后访问内部作用域中的变量:

var _this = this;

someMethod(function() {
  console.log(this);  // => window
  console.log(_this); // => Outer scope
});

当您需要访问内部和外部范围时,这种方法很好。但是内部作用域没有任何用处,所以我们可以写得更短:

someMethod(function() {
  console.log(this); // Outer scope
}.bind(this));

.bind() 方法在 anon 函数的外部作用域中执行。它将函数绑定(bind)到外部范围。因此,函数的内部作用域将与外部作用域相同,您可以像往常一样使用 this,就好像作用域没有改变一样。

在 CoffeeScript 中,您可以使用粗箭头留在外部作用域中:

_this = this

someMethod ->
  console.log this  # winodw
  console.log _this # Outer scope
someMethod =>
  console.log this     # Outer scope
  console.log ` this ` # You can still access window like ` this `, pun intended

在 ES6 中你也可以使用粗箭头:

foo( () => {
  console.log(this);
});

请注意,虽然像在 CoffeeScript 中一样,粗箭头维护着外部作用域,但这意味着不同的东西!在 ES6 中,粗箭头创建了一个无法拥有自己作用域的假函数。

这很重要,因为一些库通过将回调应用到特定范围来与回调通信,并希望您对其执行 this.something()。它不适用于 ES6 粗箭头(好吧,它在技术上可以与 Babel 一起使用,因为 Babel 将 ES6 粗箭头转换为传统函数,但你不应该依赖它)。

有关 .bind() 的更多信息,请参阅 Function.prototype.bind() on MDN .

关于javascript - 当您在 Ember 函数上绑定(bind) 'this' 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100243/

有关javascript - 当您在 Ember 函数上绑定(bind) 'this' 时会发生什么?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  9. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐