如何访问 Backbone.js 类中 jQuery 小部件的实例属性?
我正在开发一个内部使用 Backbone.js 的 jQuery 小部件。
这里集合创建模型,视图创建自己的子视图:
Serializer = function(options, element){
this.element = element;
this.data = options.data;
this.collection = new Serialize.Collection(this.data);
this.view = new Serialize.View({ el: this.element, collection: this.collection });
};
$.widget.bridge("serialize", Serializer);
$.widget.bridge 提供了一个友好的包装器,用于创建小部件的实例并传入选项(这里的 @vars
由 Rails 设置):
$('#item').serialize({
data: <%= @data %>,
name: '<%= @name %>',
keys: '<%= @keys %>'
});
稍后创建的模型和视图需要访问小部件的选项 实例。到目前为止,我通过在集合本身上设置选项来解决这个问题:
this.collection = new Serialize.Collection(this.data, options);
并在以后需要它们的地方(例如在视图中)引用它们:
var keys = this.model.collection.keys
但这会变得混乱并且不那么灵活。
对于单个实例,您可以设置 Serialize.Config = { // options }
,并全局访问它。但对于多个实例,每个实例都需要自己的配置。
所以我的问题是,是否有一种干净的方法来访问 Backbone 类中的小部件实例及其选项,而不将其作为参数传递?
I'm working on a jQuery widget that internally uses Backbone.js.
Here the collection creates the models, the view creates its own subviews:
Serializer = function(options, element){
this.element = element;
this.data = options.data;
this.collection = new Serialize.Collection(this.data);
this.view = new Serialize.View({ el: this.element, collection: this.collection });
};
$.widget.bridge("serialize", Serializer);
$.widget.bridge provides a friendly wrapper for creating instances of the widget and passing in options (here the @vars
are set by Rails):
$('#item').serialize({
data: <%= @data %>,
name: '<%= @name %>',
keys: '<%= @keys %>'
});
The models and views created later need access to the options of the widget instance. I solved this so far by setting the options on the collection itself:
this.collection = new Serialize.Collection(this.data, options);
And referencing them later where they are needed (e.g. in a view):
var keys = this.model.collection.keys
But this gets messy and is not that flexible.
For a single instance you could set Serialize.Config = { // options }
, and access it globally. But for multiple instances, each instance needs its own config.
So my question is, is there a clean way to access the widget instance and its options within the Backbone classes, without passing it as an argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎您想根据传递给小部件的选项来渲染每个小部件实例。
按照惯例,Backbone.js 视图是存储这些选项的好地方。特别是因为每个小部件只有一个视图。
因此,我会执行以下操作:
当您渲染小部件时(大概使用
this.view.render()
),您可以访问传递给Serializer
的所有选项:It seems as if you would like to render each widget instance based on the options you pass to the widgets.
Backbone.js Views are by convention a good place to store these options. Especially since you have one view per widget.
Thus, I would do the following:
When you render the widget (presumably with
this.view.render()
) you have access to all the options you passed intoSerializer
: