开发者

Trying to implement a default base class in javascript not sure its correct

I come from a C++/Java background, but I'm having problems getting the syntax right on this javascript. This is what I was trying to accomplish. I w开发者_Python百科ant a base class TemplateBaseView which inherits from Backbone.View. The TemplateBaseView overrides the initialize and render function from the Backbone.View. I am also using underscore.js. Here is a brief attempts, any help would be appreciated.

  function TemplateBase(){}
  TemplateBase.prototype.render = function(){ ... }
  TemplateBase.prototype.initialize = function(){ ... }
  _.extend( TemplateBase , Backbone.View );

And I essentially want to do something like this,

var HeaderView = TemplateBase({ template: _.template($("#header_template").html())};

which would create a Backbone.View object essentially with the default render and initialize function and the template attribute specified.

Any help?


You want to use the built in extend from backbone.

var TemplateBase = Backbone.View.extend({
  'this': 'is',
  'a': 'class'
});

var HeaderView = new TemplateBase;

A couple things. You can refer to TemplateBase as a 'class' but there's really no such thing in javascript, that's just a useful name for people coming from class based languages. It's technically a prototype.

Next: Remember to use new when you create an instance of TemplateBase, otherwise you're just invoking a function and setting your object to whatever that function returns, rather than an instance of that prototype.

Finally, just a convention, most people would capitalize their 'classes' but not their instances. So I could change HeaderView to headerView

edit

After reading your question again, maybe you want HeaderView to be a class? In which case:

var HeaderView = TemplateView.extend({
  template: _.template( $("#header_template").html())
});

var headerInstance = new HeaderView;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜