Javascript 在不同视图之间共享相同的操作/功能
假设我有不同的视图,每个视图都有特定于某个项的DOM事件Javascript 在不同视图之间共享相同的操作/功能,javascript,backbone.js,Javascript,Backbone.js,假设我有不同的视图,每个视图都有特定于某个项的DOM事件事件:{“dblclick div.editable”:“edit”} 我想在不同的视图之间共享功能编辑(然后保存) var View1 = Backbone.View.extend({ events: { "dblclick div.editable": "edit" }, edit: function () {} // function I would like to share btw diff views }
事件:{“dblclick div.editable”:“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
});
有可能吗?
最好的方法是什么?
有一些例子吗 上的介绍了如何使用Mixins来解决此设计问题:
问题是:有时您对多个应用程序具有相同的功能
对象,将对象包装在父对象中是没有意义的
对象例如,如果有两个视图共享方法,但
不要——也不应该——拥有共享的父视图
解决方案:对于这个场景,使用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)
}));
在上,描述了如何使用Mixins来解决这种设计问题:
问题是:有时您对多个应用程序具有相同的功能
对象,将对象包装在父对象中是没有意义的
对象例如,如果有两个视图共享方法,但
不要——也不应该——拥有共享的父视图
解决方案:对于这个场景,使用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)
}));
即使我认为@IntoTheVoid更优雅,我还是想公开一种非常简单的方法:一个Utils模块:
var App = function(){};
App.Utils = {
myCommonFunction: function( param ){
// code
}
}
var View1 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function() {
App.Utils.myCommonFunction( "param" );
}
});
var View2 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function() {
App.Utils.myCommonFunction( "param" );
}
});
即使我认为@IntoTheVoid更优雅,我还是想公开一种非常简单的方法:一个Utils模块:
var App = function(){};
App.Utils = {
myCommonFunction: function( param ){
// code
}
}
var View1 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function() {
App.Utils.myCommonFunction( "param" );
}
});
var View2 = Backbone.View.extend({
events: { "dblclick div.editable": "edit" },
edit: function() {
App.Utils.myCommonFunction( "param" );
}
});