我有几个视图,我有一些常见的代码要抽象到自定义的Backbone.View类中。这样做有什么最佳做法吗?
是一个很好的模式来做这样的事情? :
// Base Grid view
var GridView = Backbone.View.extend({
initialize : function(){
//common view init code ..
//do the plug in overrides
if (options.addHandler)
this.addHandler = options.addHandler;
if (options.events)
//?? extend default events or override?
this.events = $.extend(this.events, options.events);
},
addHandler : function() {
//defaulthandler this code can be overridden
});
});
// in another object create some views from the GridView base
....
var overrides = { events:"xxx yyy", el: ulElement addHandler: myAddFunction }
var UserList = GridView.extend(overrides)
var userList = new UserList(users, options);
....
var coursesOverrides : {addHandler: ...}
var coursesOptions: {el: courseElement, ...}
var CourseList = GridView.extend(coursesOverrides)
var courseList= new CourseList (courses, coursesOptions)
// along the same lines maybe there's an abstraction for toolbar views
var ClassToolbarView = ToolbarBase.extend(toolOverrides)
var classtoolbar = new ClassToolbarView(actions, toolbaropts)
对于扩展View以重构公共视图代码的任何指示,我们都很感激。
答案 0 :(得分:4)
首先,我没有看到您initializer()
中传递的选项,因此这是一个错误。
其次,.extend()
方法是继承的:
var GridView = Backbone.View.extend({ ... })
var GridViewWithNewFunctionsAndEvents = GridView.extend({ ... })
您可以替换或扩展GridView的功能,并调用new GridViewWithNewFunctionsAndEvents()
并在您需要的新对象中获得额外的功能,就像扩展Backbone stock View类一样。
如果需要扩展初始化程序,可以这样做来调用超类的初始化程序:
var GridViewWithNewFunctionsAndEvents = GridView.extend({
initializer: function(options) {
GridView.prototype.initializer.call(this, options);
/* Your stuff goes here */
}
});