在另一个 Marionette.ItemView 中调用函数 [英] Call a function in another Marionette.ItemView

查看:21
本文介绍了在另一个 Marionette.ItemView 中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ItemView,我在其中使用 clearSearch() 函数.我需要在另一个 ItemView 中调用相同的函数,因此为了保持干燥,我尝试调用 clearSearch(),但我没有工作.

I have one ItemView, where I use clearSearch() function. I need to call the same function in another ItemView, so to keep it DRY I tried to call clearSearch(), but i didn't work.

View.Panel = Marionette.ItemView.extend({
    template: panelTpl,
    events: {
        'click .search_clear': 'clearSearch',
    }
    clearSearch: function() {
        //some important actions
    }
});

View.Pagination = Marionette.ItemView.extend({
    template: paginationTpl,
    events: {
        'click .page': 'changePage'
    },
    changePage: function(e) {
        //others important actions
        clearSearch();
    }
});

我也尝试使用 View.Panel.clearSearch(),但是我遇到了这个错误:

I also tried to use View.Panel.clearSearch(), but I've got this error:

Uncaught TypeError: Object function (){return i.apply(this,arguments)}没有方法clearSearch"

Uncaught TypeError: Object function (){return i.apply(this,arguments)} has no method 'clearSearch'

.

推荐答案

使用事件.

定义一个全局事件总线:

define a global event bus:

Event.Dispatcher = _.clone(Backbone.Events);

并在您的分页视图中.

View.Pagination = Marionette.ItemView.extend({
  template: paginationTpl,
  events: {
    'click .page': 'changePage'
  },
  changePage: function(e) {
    //notify page change event
    Event.Dispatcher.trigger("pageChanged", [pass any data you want to pass]);
  }
});

在您的面板视图中,收听此事件,并定义如何处理它.

in your panel view, listen to this event, and define how to handle it.

View.Panel = Marionette.ItemView.extend({
  template: panelTpl,
  events: {
    'click .search_clear': 'clearSearch',
  },
  initialize: function() {
    //listen to that event
    this.listenTo(Event.Dispatcher, 'pageChanged', this.clearSearch);
  },
  clearSearch: function() {
    //some important actions
  }
});

我对 Marionette 没有任何经验.使用 Marionette 可能有更简单的方法来实现这一点,但这是我在纯香草主干应用程序中一直使用的模式.

I don't have any experience with Marionette. There may be easier ways to implement this with Marionette, but this is the pattern I've been using in my pure vanilla backbone applications.

这篇关于在另一个 Marionette.ItemView 中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆