Subclasses of Backbone.View

I have several views that share a common code that I would like to abstract into the custom Backbone.View class. Are there any recommendations for this?

is a good sample to do something like this?

// 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 an abstraction for toolbar views var ClassToolbarView = ToolbarBase.extend(toolOverrides) var classtoolbar = new ClassToolbarView(actions, toolbaropts) 

It’s clear that any pointers to good examples of extending the view to refactor the code of the general view.

+4
source share
1 answer

Firstly, I do not see the options passed in your initializer() , so there is an error.

Secondly, the .extend() method is inherited:

 var GridView = Backbone.View.extend({ ... }) var GridViewWithNewFunctionsAndEvents = GridView.extend({ ... }) 

And you can replace or extend the functionality of the GridView and call new GridViewWithNewFunctionsAndEvents() and get additional functionality in the new object that you need, just like you extend the Backbone Stock View class.

If you need to extend the initializer, you can do this to call the initializer over the superclass:

  var GridViewWithNewFunctionsAndEvents = GridView.extend({ initializer: function(options) { GridView.prototype.initializer.call(this, options); /* Your stuff goes here */ } }); 
+4
source

Source: https://habr.com/ru/post/1395527/


All Articles