使用了Backbone 也有了一段时间, 只是以前调用确定的使用一套方案,调研完毕之后直接交给下面人用去了,于是也没有继续深入
最近又看了reactjs,很羡慕继承,想整合到项目中,但是用reactjs目前还不现实,多希望Backbone 也能拥有这样的特性,于是就查看Backbone中的继承到底是怎么回事。
以下是Backbone 中的extend源码部分
// Helper function to correctly set up the prototype chain for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent constructor.
if (protoProps && _.has(protoProps, ‘constructor‘)) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`‘s constructor function and add the prototype properties.
child.prototype = _.create(parent.prototype, protoProps);
child.prototype.constructor = child;
// Set a convenience property in case the parent‘s prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
backbone 文档中这样写道
extendBackbone.View.extend(properties, [classProperties])
Get started with views by creating a custom view class. You‘ll want to override therender function, specify your declarative events, and perhaps the tagName,className, or id of the View‘s root element.
var DocumentRow = Backbone.View.extend({
tagName: "li",
className: "document-row",
events: {
"click .icon": "open",
"click .button.edit": "openEditDialog",
"click .button.delete": "destroy"
},
initialize: function() {
this.listenTo(this.model, "change", this.render);
},
render: function() {
...
}
});
Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime.
于是写了很长时间 Backbone.View.extend, 很悲催,看了源码之后才知道 parent = this; 于是打开思维 其实VIEW也可以这样写的var A = Backbone.View.extend({
name:‘name‘,
initialize:function(){console.log(this.addr)
//this.render();
},
test:function(){
return this.name;
},
render:function(){
var $div = $(‘<div id="test-bean"></div>‘);
console.log("render2");
$(‘body‘).append($div);
}
})
var b = A.extend({
addr:"wxi",
initialize:function(){
A.prototype.initialize.call(this);console.log(‘b‘)
this.render();
},
getAddr:function(){
return this.addr;
},
render:function(){
A.prototype.render.call(this);
console.log("render");
},
});
console.log(b.prototype)
var bb = new b();
console.log(bb.test());
打开思维,这样我们就可以做很多很多~~ ,具有特性的VIEW封装...
原文:http://my.oschina.net/u/1156053/blog/531503