我在 Backbone 中有一个项目,我正在使用 require js(我对 require 没有太多经验,实际上这是我的第一个项目)。
现在。在我的 home.js View 中,我有很多这样的函数
iScroll: function () {
window.scrollers.myScroll = new iScroll(this.$('#products_container')[0], {
vScrollbar: true,
onScrollStart: function () {...........
swipeMobile: function () {
$("#mobile_view").swipe({
swipe: function (event, direction, distance, duration, fingerCount) {
if (direction == "left") {....
我想将所有这些功能放在一个单独的模块中,例如“插件”,并在需要时在我的 home.js View 中调用我需要的功能。
我像这样在主视图上加载我的模板
define([
'text!templates/about.html',
'text!templates/home.html',
'text!templates/product.html',
'text!templates/contact.html',
'collections/products'
],
function (aboutTemplate, homeTemplate, productTemplate, contactTemplate, Products) {
最简单的方法是什么?
最佳答案
如果您的函数集合是主干模型、集合或 View 的扩展,您可以执行以下操作:
define(['backbone'], function( Backbone ) {
return Backbone.View.extend({
customMethod: function() {
return this;
}
});
});
然后只需要文件的路径,你就可以像这样使用它:
require(['path/to/custom/view'], function( CustomView ) {
var customview = new CustomView();
customview.customMethod(); // returns the Backbone view
});
编辑:如果您有一些不是模型、集合或 View 的代码,您可以改为这样做(假设这是一个没有依赖关系的模块):
define(function() {
var MyCustomHelper = function() {
this.someattribute = true;
};
MyCustomHelper.prototype.customMethod = function() {
return this.someattribute;
};
return MyCustomHelper;
});
关于javascript - 创建需要 JS 模块,主干,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481049/