javascript - Marionette.js - 从 itemView 访问行为函数

标签 javascript backbone.js marionette

起初我有 Marionette.js itemView,里面有很多功能。所以,我想将其中一些转移到行为中。但我遇到了大问题 - 我无法直接使用 itemView 中的行为函数。这是我的初始代码:

var NodeView = Marionette.ItemView.extend({
    showDefault: function(){
        /* some code */
        this.showOther();
    },
    // Initiates
    showOther: function(){
        /* some code */    
    }
});

正如你所见,我在另一个节点中触发了一个节点方法。在行为内部移动一个函数后我需要做同样的事情

var NodeView = Marionette.ItemView.extend({
    behaviors: {
        NodeBehavior: {
            behaviorClass: NodeBehavior
        }
    },
    showDefault: function(){
        /* some code */
        this.showOther(); /* how can i trigger this function ? */
    }        
});

var NodeBehavior = Marionette.Behavior.extend({
    showOther : function(){
        /* some code */    
    }    
});

最佳答案

从您的 Angular 来看,您可以使用 triggerMethod 手动调用行为中的方法

例如,这是一个附加了 Modal 行为的模拟 View 。假设在初始化时我们想要调用 Modal 行为的 onSayWho 方法。以下代码演示了如何执行此操作:

define([
    'marionette',
    'behaviors/Modal',
    'tpl!templates/tpl.html'
], function(
    Mn,
    Modal,
    tpl
) {
  var view = Mn.LayoutView.extend({
    template: tpl,

    behaviors: {
        Modal: {
            behaviorClass: Modal
        }
    },

    initialize: function(options) {
        var data = 'Mike Jones!';
        this.triggerMethod('sayWho', data);
    },
});

return view;
});

这里是模态行为代码:

define([
    'marionette'
], function (
    Mn
) {
   var Modal = Mn.Behavior.extend({
     onSayWho: function(name) {
         console.log('who? ' + name);
     }
});

return Modal;
});

请务必注意,行为的函数名称前面需要有 on 。 IE View 调用 this.triggerMethod('sayWho', data),而行为中的实际函数名称是 onSayWho

关于javascript - Marionette.js - 从 itemView 访问行为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902885/

相关文章:

javascript - 在 DOM 中的元素之前绑定(bind) Rivets.js

backbone.js - 在 onClose 处理程序中触发时 ItemView 事件不起作用

javascript - 主干同步问题触发 POST 而不是 PUT

javascript - 如何确定光标在表单元素的字符串中的位置?

javascript - Backbone JS事件函数修改对象

javascript - 如何将 jquery 选择传递到函数中?

javascript - 使用下划线、_.extend 关键字的 Mixin 模式

javascript - 使用 backbone.marionette 和 requireJs 的网络应用程序的循环依赖

javascript - 在Web应用程序中将多行插入mysql

Javascript - 窗口打开,使用 CDN