gpt4 book ai didi

javascript - 主干 View 中的私有(private)事件处理程序

转载 作者:行者123 更新时间:2023-11-29 22:16:43 26 4
gpt4 key购买 nike

我正在尝试找出一种方法来使我的私有(private)函数和辅助方法真正私有(private)。每个对象应该只公开允许在外部调用的内容(激进,我知道!)。我很难以以下方式使用 Backbone View 执行此操作:

  1. 不牺牲可读性
  2. 不涉及很多样板文件
  3. 没有任何意想不到的后果

这是我的一般 View 结构:

(function(){
//Private function no other view needs to care about
var addStuffToMyDom = function(model){
var newView = new Subview({model: model});

//Problem: this doesn't refer to the 'view' here
this.$el.append(newView.render().$el);
}

//Another trivial function which should really be private
var doSomeThingTrivial = function(){
this.$el.addClass("meh");
}

return BaseView.extend({
events: {
"click": doSomeThingTrivial
},

render: function(){
var me = this;
this.collection.each(addStuffToMyDom);
return this;
}
});
}());

如您所见,私有(private)函数无法引用“this”以将其附加到。

解决方案一:

(function(){
var me;

...

return BaseView.extend({
initialize: function(){
me = this;
}
});
}());

这有很多微妙的副作用 + 每次都必须这样做会很烦人。

解决方案 2:

(function(){
var me;

...

return BaseView.extend({
events{
"click" : function(){
doSomeThingTrivial.call(this);
}
}
});
}());

这行得通,但是它有很多用于困惑代码的样板。

解决方案 3:

(function(){
return BaseView.extend({
events: {..}
initialize: function(){
_.bindAll(this, this.events);
}
});
}());

我最喜欢这个;这是有效的,可读性很强,并且像宣传的那样工作,但同样,对于每个 View 来说,这是一个额外的步骤。我还缺少其他解决方案吗?

最佳答案

您可以将要使用的上下文传递给 each 方法:

this.collection.each(addStuffToMyDom, this);

现在 this 将成为您在 addStuffToMyDom 中的 View 。

我认为当您使用 Backbone 事件哈希来连接事件时,它会做类似的事情。您确定 this 不是 doSomeThingTrivial 中的 View 吗?

如果您查看 Backbone delegateEvents,它会执行以下操作:

method = _.bind(method, this);

this 是您的 View 。

关于javascript - 主干 View 中的私有(private)事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737091/

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