这是我的行为:
/**
* @class Filter
* @classdesc Holds filtering behavior for menu views
* @extends Marionette.Behavior
*/
define(['marionette', 'eventer'], function (Marionette, eventer){
'use strict';
var Filter = Marionette.Behavior.extend({
defaults: {
field: "name"
},
initialize: function () {
this.listenTo(eventer, 'menu:filter', this.onFilter, this);
},
/**
* Checks each item's configured field_name (name, group_name, etc) to see if there are any
* to show and to hide the non-matching terms
* @method Filter.onFilter
* @param {string} term
*/
onFilter: function (term) {
console.log(term);
// if term is blank, render item
if(term === "") {
this.$el.show();
}
var pattern = new RegExp(term, "gi"),
model = this.view.model,
shouldShow = pattern.test(model.get(this.options.field));
this.$el.toggle(shouldShow);
}
});
return Filter;
});
这是我的测试:
describe("#onFilter()", function () {
it.only("should show the item based on the field and term passed in", function () {
var view = new Marionette.ItemView({
model: new Backbone.Model({ name: "foo", id: "1", checked: false, active_count: 10 }),
template: under.template(templateHTML),
tagName: 'article',
behaviors: {
FilterBehavior: {
behaviorClass: FilterBehavior
}
}
});
view.render();
FilterBehavior.prototype.onFilter('foo');
assert.equal(view.$el.css('display'), 'block');
view.destroy();
});
});
我不断收到的错误是TypeError: 'undefined' is not an object (evaluating 'this.view.model')
. 任何人都知道 1)为什么会抛出这个错误,以及 2)如果这是测试 Marionette.Behavior 的正确方法吗?