Reputation: 773
At first i had Marionette.js itemView with plenty functions inside. So, i would like to move some of them to Behavior. But i have met big problem - i can't use behavior functions from itemView directly. Here is my initial code:
var NodeView = Marionette.ItemView.extend({
showDefault: function(){
/* some code */
this.showOther();
},
// Initiates
showOther: function(){
/* some code */
}
});
as u see i trigger one node method inside other. I need do same after moving one function inside behavior
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 */
}
});
Upvotes: 0
Views: 1234
Reputation: 650
From your view you can manually call methods within a behavior by using triggerMethod
For example, here is a mock view with a Modal
behavior attached. Assume upon initialization we would like to call the onSayWho
method on the Modal behavior. The following code demonstrates how you would do that:
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;
});
and here would be the Modal behavior code:
define([
'marionette'
], function (
Mn
) {
var Modal = Mn.Behavior.extend({
onSayWho: function(name) {
console.log('who? ' + name);
}
});
return Modal;
});
Be sure to note that the behavior's function name needs to have on
before it. IE the view calls this.triggerMethod('sayWho', data)
, whereas the actual function name in the behavior is onSayWho
Upvotes: 2
Reputation: 2155
Is the NodeView
and NodeBehavior
defined in the same file like that?
You will need to have your NodeBehavior defined above your NodeView:
var NodeBehavior = Marionette.Behavior.extend({
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 ? */
}
});
Otherwise, NodeBehavior isn't defined when you are setting behaviorClass: NodeBehavior
Upvotes: 0