gpt4 book ai didi

javascript - Backbone : How to bind arguments for listenTo-callback?

转载 作者:搜寻专家 更新时间:2023-11-01 05:01:27 25 4
gpt4 key购买 nike

是否可以为 listenTo 回调绑定(bind)函数参数?

到目前为止,我已经添加了一个包装器方法“myHandler”,我想摆脱它:

// Basic marionette layout
var view = Marionette.Layout.extend({

initialize: function() {
// wrapping view logic inside a custom object
this.controller = new MyViewController();
},

// creates a sub view and adds event handlers
someFunc: function() {
var subView = new MySubView();

// HERE: how to bind args for callback?
this.listenTo(subView, "myEvent", this.myHandler, this);
},

// this is a dummy wrapper that I want to remove
myHandler: function(e) {
this.controller.handleIt(this, e);
},

我想做的是:

someFunc: function() {
var subView = new MySubView();

// here wrapIt binds 'this' as first argument for handleIt
this.listenTo(subView, "myEvent",
wrapIt(this.controller.handleIt, this), this);
}

最佳答案

listenTo 只接受 3 个参数。如果您需要将函数绑定(bind)到某个对象,那么跨浏览器的方法是使用下划线 _.bind 函数:

this.listenTo(subView, "myEvent", _.bind(this.myHandler, this))

但是它几乎不需要,因为您调用 listenTo 的对象是默认上下文。要阅读更多内容,请参阅这些 github 问题:

关于javascript - Backbone : How to bind arguments for listenTo-callback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16294227/

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