应该 Jquery 组件 return false
Should Jquery Component return false
我正在尝试使用 BDD(行为驱动开发)创建一个 jquery 模块。
这是我的组件
(function($) {
function MyModule(element){
return false;
}
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
new MyModule(this);
});
};
$.fn.myModule.Constructor = MyModule;
})(window.jQuery);
这是我的测试
QUnit.test( "test", function( assert ) {
assert.expect(1);
var smallBox = $('<div/>',{'id':'smallBox'}).width(200).height(200);
var result = smallBox.myModule();
console.log(result); // This gives the HTML element itself but I am expecting it must be boolean false
assert.notOk(result, "should return false" );
});
我有 2 个问题。
1- 如果我的组件 return 是布尔值怎么办。是模式错误吗?
2- 我如何从我的组件return 布尔值
那是因为您没有 returning new MyModule
,您 returning 了 this.each
的 returned 值,这是一个jQuery 对象。如果你想要一个布尔值,你必须 return 一个布尔值。像这样:
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() { // don't return here because then you'll return a jQuery object
new MyModule(this);
});
return false; // return a boolean (works)
};
从回调内部返回不影响父函数的 returned 值。
我正在尝试使用 BDD(行为驱动开发)创建一个 jquery 模块。
这是我的组件
(function($) {
function MyModule(element){
return false;
}
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
new MyModule(this);
});
};
$.fn.myModule.Constructor = MyModule;
})(window.jQuery);
这是我的测试
QUnit.test( "test", function( assert ) {
assert.expect(1);
var smallBox = $('<div/>',{'id':'smallBox'}).width(200).height(200);
var result = smallBox.myModule();
console.log(result); // This gives the HTML element itself but I am expecting it must be boolean false
assert.notOk(result, "should return false" );
});
我有 2 个问题。
1- 如果我的组件 return 是布尔值怎么办。是模式错误吗?
2- 我如何从我的组件return 布尔值
那是因为您没有 returning new MyModule
,您 returning 了 this.each
的 returned 值,这是一个jQuery 对象。如果你想要一个布尔值,你必须 return 一个布尔值。像这样:
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() { // don't return here because then you'll return a jQuery object
new MyModule(this);
});
return false; // return a boolean (works)
};
从回调内部返回不影响父函数的 returned 值。