javascript 如何从单独文件中的另一个视图调用主干视图函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26861006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:36:28  来源:igfitidea点击:

How to call a backbone view function from another view in separate files

javascriptbackbone.jsviews

提问by ConfuXigrator

I have two backbone views defined in two separate files namely: LandingView.js

我在两个单独的文件中定义了两个主干视图:LandingView.js

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'text!templates/landing/landingTemplate.html',
    'text!templates/invitations/invitationsTemplate.html',
    'views/invitations/InvitationsView',
], function ($, _, Backbone, Marionette, landingTemplate, invitationsTemplate, InvitationsView) {
var LandingView = Backbone.View.extend({
        el : $("#landing"),
        id : 'landing',
        transition : 'slide',

        initialize : function () {              
            this.GetNotificationsCounts();
        },
        events : {
            'click #invitations' : 'onInvitations',

        },
        render : function () { 
            var that = this;
            $('.menu li').removeClass('active');
            $('.menu li a[href="#"]').parent().addClass('active');

            this.$el.html(landingTemplate);

        },
        cleanup: function() { 
            this.undelegateEvents();
            $(this.el).empty();
        },
        onInvitations : function () { 

            //do something
        },

        GetProfile: function (userLogin) {
               // do something
        },


        GetNotificationsCounts: function () {
               // do something

        },

        formatAccountName: function () {
             //do something
        }


    });

return LandingView; });

Then there is another file InvitationsView.js

然后还有一个文件 InvitationsView.js

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'views/landing/LandingView',
    'text!templates/invitations/invitationsTemplate.html',
], function ($, _, Backbone, Marionette, LandingView, invitationsTemplate ) {


var InvitationsView = Backbone.View.extend({
        el : $("#invitations"),
        id : 'invitations',
        transition : 'slide',

        initialize : function () { debugger;

            this.$el.attr('data-transition', this.transition);
            this.currentUserLogin = currentUserLogin;
            var that = this;

        },
        events : {

        },
        render : function () { debugger;
            $('.menu li').removeClass('active');
            $('.menu li a[href="#"]').parent().addClass('active');

            this.GetUserInvitationDetails();

             this.$el.html(invitationsTemplate);

        },
        cleanup: function() { 
            this.undelegateEvents();
            $(this.el).empty();
        },

        GetUserInvitationDetails: function () {

            var landingView =  new LandingView();
            currentUserName= landingView.formatAccountName();
            curUser = currentUserName.replace("\", "^").replace("^", "%5E");

            var profilemsg = landingView.GetProfile(currentUserName);

        },

    });

return InvitationsView;});

Now I need to call the formatAccountName and GetProfile functions defined in the first JS to the second JS. I am unable to do that. I get errors. When I try

现在我需要将第一个 JS 中定义的 formatAccountName 和 GetProfile 函数调用到第二个 JS。我无法做到这一点。我收到错误。当我尝试

var landingView = new LandingView(); currentUserName= landingView.formatAccountName();

varlandingView = new LandingView(); currentUserName=landingView.formatAccountName();

This also fails. Can somebody help me in this regard and tell me how can I achieve this

这也失败了。有人可以在这方面帮助我并告诉我如何实现这一目标

回答by KarlPurk

Your current approach of calling the formatAccountNamemethod works. The following jsfiddle shows this:

您当前调用该formatAccountName方法的方法有效。以下 jsfiddle 显示了这一点:

http://jsfiddle.net/v4h11qac/

http://jsfiddle.net/v4h11qac/

The problem is likely caused by another error that has not been handled correctly, resulting in the code not being run. You should fix the existing errors and the method call should work as expected.

问题很可能是由于另一个错误没有得到正确处理,导致代码无法运行。您应该修复现有错误,并且方法调用应该按预期工作。

Orignal Answer:

原答案:

You could call the method directly on the prototype object:

您可以直接在原型对象上调用该方法:

LandingView.prototype.formatAccountName();

If you need to pass through a new context you can use the callor applymethod as below:

如果你需要通过一个新的上下文,你可以使用callorapply方法如下:

LandingView.prototype.formatAccountName.call(context);

A better approach might involve creating a helper module that can be shared by both views.

更好的方法可能涉及创建一个可以由两个视图共享的帮助程序模块。

var viewHelpers = {
    formatAccountName: function(account) {
        // ...
    }
};

var ViewOne = Backbone.View.extend({
    render: function() {
        var formattedName = viewHelpers.formatAccountName(this.model);
        // ...
    }
};


var ViewTwo = Backbone.View.extend({
    render: function() {
        var formattedName = viewHelpers.formatAccountName(this.model);
        // ...
    }
};

You could also use a system bus, however that may be a little too heavy for such a use case. If you want to take a look at that path, then Backbone.Radioprovides a request/response pattern which could be used to fulfill this requirement.

您也可以使用系统总线,但是对于这样的用例来说可能有点太重了。如果您想查看该路径,则Backbone.Radio提供了可用于满足此要求的请求/响应模式。

回答by user2952238

You could use a global event dispatcher that you declare in some kind of main-js-file like this:

您可以使用在某种 main-js 文件中声明的全局事件调度程序,如下所示:

var vent = _.extend({}, Backbone.Events);

Then in your view, listen for an event and run function.

然后在您的视图中,侦听事件并运行函数。

vent.on('your:event',this.function_to_run_from_other_view,this);

Dispatch the event like this from the other view.

从另一个视图发送这样的事件。

vent.trigger('your:event',args)