假设我有不同的 View ,每个 View 都有特定于某个项目的 DOM 事件 events: { "dblclick div.editable": "edit"}
我想在不同 View 之间共享功能edit
(然后还保存)。
var View1 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function () {} // function I would like to share btw diff views
});
var View2 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function () {} // function I would like to share btw diff views
});
有可能吗?
最好的方法是什么?
有一些例子吗?
最佳答案
关于Backbone patterns site描述了如何使用Mixins来解决这种设计问题:
The problem: Sometimes you have the same functionality for multiple objects and it doesn't make sense to wrap your objects in a parent object. For example, if you have two views that share methods but don't -- and shouldn't -- have a shared parent view.
The solution: For this scenario, it's appropriate to use a mixin.
所以在这种情况下它可能是这样的:
App.Mixins.Editable = {
edit: function() { /* ... */ },
open: function() { /*... */ },
close: function() { /* ... */ }
};
App.Views.YourEditPage = Backbone.View.extend(
_.extend({}, App.Mixins.Editable, {
events: { "dblclick div.editable": "edit" },
// (Methods and attributes here)
}));
关于javascript - 在不同 View 之间共享相同的操作/功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10536882/