Backbone.js嵌套视图:引用还是事件?
更有效的方法是,使用事件在嵌套视图之间通信,或者保留引用以调用方法。下面的示例显示了两个视图。外部视图响应单击事件,然后可以使用事件或方法调用来使内部视图做出适当的响应Backbone.js嵌套视图:引用还是事件?,backbone.js,Backbone.js,更有效的方法是,使用事件在嵌套视图之间通信,或者保留引用以调用方法。下面的示例显示了两个视图。外部视图响应单击事件,然后可以使用事件或方法调用来使内部视图做出适当的响应 InnerView = Backbone.View.extend({ initialize: function() { this.model.bind('doSomethingEvent', this.doSomething); }, doSomething: function() {
InnerView = Backbone.View.extend({
initialize: function() {
this.model.bind('doSomethingEvent', this.doSomething);
},
doSomething: function() {
// This could have been called from event/trigger
// or from direction method invocation using reference.
}
});
OuterView = Backbone.View.extend({
events = {
'click' : 'handleOutViewClick'
},
render: function() {
// Create InnerView to render some model
var innerView = new InnerView({model:this.model });
$(this.el).append(innerView.render().el);
// Could store a reference to the View?
this.viewRef = innerView;
},
handleOutViewClick: function(e) {
// Should this function use a reference to the InnerView instance:
this.viewRef.doSomething();
// Or should it trigger an event on this.model that
// the InnerView is bound to?
this.someCollection.trigger('doSomethingEvent');
}
});
一个方法调用可能比事件分派更有效,事件分派至少涉及两个方法调用。但我不认为你需要关心技术上哪个更“有效”。除非这种情况在一秒钟内发生多次,否则您只能关心哪些代码更干净、更正确。我认为最干净的模式取决于沟通的细节。以下是我的偏好:
一个方法调用可能比事件分派更有效,事件分派至少涉及两个方法调用。但我不认为你需要关心技术上哪个更“有效”。除非这种情况在一秒钟内发生多次,否则您只能关心哪些代码更干净、更正确。我认为最干净的模式取决于沟通的细节。以下是我的偏好: