在主干中调用超类方法
Calling super class method in Backbone
var BaseView = Backbone.View.extend({
localizedTemplate : function (element) {
template = _.template(element.html());
return function (data) {
return template($.extend({}, data, resource));
};
}
});
var DerivedView = BaseView.extend({
initialize: function (options) {
this.model = options.model;
this.template = function () {
return this.localizedTemplate($("#someTemplate"));
};
},
render: function () {
var output = this.template(this.model.toJSON());
this.$el.append(output);
return this;
}
});
为什么上面的代码不起作用? 为什么我无法在派生视图中调用 someFunction? 有什么方法可以实现这一点吗?
我正在使用骨干最新版本。
当你这样做时:
this.template = function () {
return this.localizedTemplate($("#someTemplate"));
};
您正在为this.template
分配一个函数。请注意,localizedTemplate
还返回一个函数:
return function (data) {
return template($.extend({}, data, resource));
};
这意味着this.template
是一个返回函数的函数,第二个函数是希望this.model.toJSON()
作为参数的函数。
您正在执行此操作:
var output = this.template(this.model.toJSON());
this.template
中的函数忽略其参数并返回一个函数,该函数将剩下以下函数:
function () {
return this.localizedTemplate($("#someTemplate"));
}
在output
.此时您可能认为output
是一块 HTML,因此您将其交给append
:
this.$el.append(output);
但是output
是一个函数,当以函数作为参数调用时,append
做什么? jQuery像这样调用该函数:
函数(索引,html(
类型:函数((
返回 HTML 字符串、DOM 元素或 jQuery 对象的函数,以插入匹配元素集中每个元素的末尾。接收元素在集合中的索引位置和元素的旧 HTML 值作为参数。在函数中,this
是指集合中的当前元素。
因此,output
函数将由jQuery的append
调用,append
将提供编译后的模板函数无法理解的参数。结果是一大堆混乱。
如果你真的想做这样的事情,那么你需要自己调用所有函数,以便你可以把正确的参数放在正确的位置:
var output = this.template()(this.model.toJSON());
// -----------------------^^
演示:http://jsfiddle.net/ambiguous/YyJLR/
或者更好的是,根本不用打扰所有额外的包装器。在视图initialize
中这样说:
this.template = this.localizedTemplate($("#someTemplate"));
然后在render
:
var output = this.template(this.model.toJSON());
演示:http://jsfiddle.net/ambiguous/BQjhS/
另请注意,您不需要this.model = options.model
,视图构造函数将为您执行此操作:
有几个特殊选项,如果传递,将直接附加到视图:
model
、collection
、el
、id
、className
、tagName
和attributes
。
var DerivedView = BaseView.extend({
someVariable: function(someData) {
return this.someFunction(someData);
}
});
- 如何在类内部调用类的方法
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- 引导程序是否有显示隐藏类的方法
- 是受(GWT)基类中方法数量影响的JavaScript对象的大小
- jQuery/can'我找不到避免代码添加类的方法
- 如何在javascript中从超类扩充方法
- Javascript继承:从超类的方法设置子类的属性
- 如何在 Javascript ES6 中向类添加方法
- Javascript:向对象类添加方法的优缺点是什么
- 类的方法 - 静态成员
- 如何查看 ExtJs 类中方法的完整列表
- 用于提取 javascript (.js) 类和方法结构的库
- 我想克隆一个 javascript 类. 将方法添加到克隆的属性中,而不实际覆盖现有方法
- 如何使用 jquery Ajax 调用调用类的方法
- Javascript类静态方法内存消耗
- 将参数传递给从另一个类调用方法的一个类上的便利方法
- 如何调用父类'方法从JavaScript中的子类中删除,以便parent's的局部变量将是可访问的
- 如何使变量在类的方法中可用
- 正确使用AngularJS ng类或替代类的方法
- 试图获得一个新的JS类来继承原来的类'方法