javascript - 创建需要 JS 模块,主干

标签 javascript backbone.js requirejs

我在 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/

相关文章:

javascript - 将文本从 IFRAME 复制到父页面上的 INPUT 字段

javascript - backbone fetch前的.css()样式不起作用-Jquery

javascript - Backbone.iobind 应该是node包还是bower包?

javascript - 主干获取()成功回调不起作用

javascript - 如何使用 RequireJS 加载依赖于 d3 的脚本?

javascript - Symfony2 是否可以使用 Javascript 删除 session 变量?

javascript - chrome.storage.local 的数据限制

javascript - 控制台返回未定义

javascript - 有什么等效的 gulp 插件可以执行 "grunt bower"吗?

javascript - 使用 requirejs 时无法调用函数