gpt4 book ai didi

javascript - 从子方法访问父对象

转载 作者:行者123 更新时间:2023-12-02 18:09:55 25 4
gpt4 key购买 nike

我的主干 View 如下:

var myView = Backbone.View.extend({
bar: 1,

open: function() {
$(window).on('resize', this.resizeHandler);
},

close: function() {
$(window).off('resize', this.resizeHandler);
},

resizeHandler: function(e) {
alert(this.bar);
}
});

this.bar 在 resizeHandler 方法中失败,因为“this”不再是对父对象的引用,而是对与事件相关的 event/html 元素的引用。

我怎样才能让它工作,以便 resizeHandler 拥有对父对象的引用,并且我仍然拥有对可以在 Jquery on 和 off 方法中使用的函数的引用?

谢谢。

最佳答案

正如 FAQ, entry Binding "this" 中所述

Perhaps the single most common JavaScript "gotcha" is the fact that when you pass a function as a callback, its value for this is lost.
With Backbone, when dealing with events and callbacks, you'll often find it useful to rely on _.bind and _.bindAll from Underscore.js.

解决您的问题的最简单方法可能是使用 _.bindAll

var myView = Backbone.View.extend({
bar: 1,

initialize: function() {
_.bindAll(this, 'resizeHandler');
},

open: function() {
$(window).on('resize', this.resizeHandler);
},

close: function() {
$(window).off('resize', this.resizeHandler);
},

resizeHandler: function(e) {
console.log(this.bar);
}
});

还有一个演示 http://jsfiddle.net/nikoshr/DZqDw/ (我建议避免使用 alert 来调试代码,尤其是在跟踪鼠标移动/调整大小事件时)

关于javascript - 从子方法访问父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com