用BackboneJS从子视图调用视图函数
Call view function from subview with BackboneJS
我想知道是否有可能从BackboneJS子视图调用视图函数。如果是,它是如何工作的?
我想从子视图中调用属于mainView的函数"hello"。
如果事件触发…
的例子:
var MainView = Backbone.View.extend({
initialize: function() {
this.$template = $(template);
this.subview = new SubView();
this.render();
},
render: function() {
this.$el.html(this.$template);
var element = this.$template.attr('id');
this.subview.setElement('#'+element).render();
},
hello: function() {
alert('Hello');
}
});
var SubView = Backbone.View.extend({
initialize: function() {
this.$template = $(template);
this.render();
},
render: function() {
this.$el.html(this.$template);
//Call view function ' hello '
//parentView.hello();
}
});
谢谢!
你可以将父视图的引用传递给子视图:
http://jsfiddle.net/puleos/hecNz/var MainView = Backbone.View.extend({
initialize: function() {
this.$template = $("<span>foo</span>");
this.subview = new SubView({parent: this});
this.render();
},
render: function() {
this.$el.html(this.$template);
var element = this.$template.attr('id');
this.subview.setElement('#'+element).render();
},
hello: function() {
alert('Hello');
}
});
var SubView = Backbone.View.extend({
initialize: function(options) {
this.$template = $("<span>bar</span>");
this.parent = options.parent;
this.render();
},
render: function() {
this.$el.html(this.$template);
this.parent.hello();
}
});
var mainView = new MainView();
console.log(mainView);
您可以尝试这样扩展MainView
:
var SubView = MainView.extend({ });
这应该给你一个MainView
中的hello
函数的引用。
或者,在SubView
中,将此添加到render
函数:
MainView.prototype.hello.call(this)
这将使用SubView
实例的上下文(模板,其他变量等)调用MainView
中的hello
函数。
相关文章:
- 从Backbone中的另一个视图调用新视图
- 从AngularJS中的视图调用控制器函数
- 从视图调用异步加载模块函数
- 从Sench Touch 2中的视图调用控制器javascript函数
- 主干 - 从我的原型视图调用方法.js
- 从 JavaFX Web 视图调用 Java 方法
- 在 Rails 中的条件下从视图调用引导模式
- 代码点火器:从视图调用模型 - 数据库内容似乎冻结
- 尝试将数据数组设置为从视图调用函数后$scope
- 从主干视图调用模板中的变量
- 如何在单独的文件中从另一个视图调用主干视图函数
- 从视图调用控制器方法
- 如何在发生更改事件时从编辑器视图调用单元格视图的render方法
- JQ Mobile:从列表视图调用具有多个参数的函数
- Backbone.js:从嵌套视图调用函数的代码不起作用
- MVC 3在JavaScript中从视图调用Action方法
- 从视图调用控制器函数!asp.net MVC
- 如何从Rails视图调用内部API(用于ReactJS预呈现程序)
- 用BackboneJS从子视图调用视图函数
- 如何从mvc视图调用java脚本函数