BackboneJS:如何从视图的事件哈希调用函数外部视图?

Mat*_*ttM 6 javascript jquery backbone.js

举个例子,这就是我要做的......

function doSomething(customParameter) {
    console.log(customParameter);
}

var MyView = Backbone.View.extend({
    // Other view stuff, skipping it...
    events: {
        'click .someClass': doSomething(customParameter)
    }
});
Run Code Online (Sandbox Code Playgroud)

这里的动机是我希望能够将变量(视图的本地)传递给视图外的其他函数.我想这样做的原因是"其他功能"只写了一次而不是四次......它会严重地保存我的项目超过100行代码.

经过大量谷歌搜索后,我还没有找到解决方案...任何想法?

谢谢!

Cri*_*hai 6

这是一种方法:

function doSomething(customParameter) {
    console.log(customParameter);
}

var MyView = Backbone.View.extend({
    // Other view stuff, skipping it...
    events: {
        'click .someClass': function(ev) { doSomething(this.customParameter); }
    }
});
Run Code Online (Sandbox Code Playgroud)

在此示例中,您声明了一个函数,该函数将本地视图所需的参数传递给该doSomething方法.


另一种方法是,如果您不想传递所有必需的参数,则使用当前视图的上下文调用doSomething():

function doSomething(ev) {
    console.log(this.customParameter); // here, the context this will be the view.
}

var MyView = Backbone.View.extend({
    // Other view stuff, skipping it...
    events: {
        'click .someClass': function(ev) { doSomething.call(this, ev); }
    }
});
Run Code Online (Sandbox Code Playgroud)

更多的OOP方法是为该公共代码提供基本视图:

var MyBaseView = Backbone.View.extend({
    doSomething: function(ev) {
        console.log(this.customParameter);
    }
});

var MyView = MyBaseView.extend({
    extends: {
        'click .someClass': 'doSomething'
    }
});
Run Code Online (Sandbox Code Playgroud)

可能有更多的方法,你只需要看看哪种方案最适合你的需求.

  • 哇,为什么我以前从未想过扩展自己的观点?我的代码本来可以更清洁.@PlanetLotus,最后一个选项可能是最适合你的. (2认同)